# encoding:utf-8
from __future__ import unicode_literals
# import os
# import sys
# nowpath = os.getcwd()
# projectPath = os.path.abspath(os.path.join(nowpath, "..\\.."))
# spiderPath = projectPath+"\\SpiderAPI\\SpiderAPI"
# sys.path.append(spiderPath)
import base64
from collections import Counter
from collections import defaultdict

from django.http import HttpResponse

# Create your views here.
from sku_analysis.Sku import SkuComent
# from sku_analysis.comment_analysis import coments_info_class


from django.contrib.auth import authenticate, login, logout

from django.contrib.auth.models import User, Permission

import os
import csv
import json
import time
import datetime
import threading
import requests
import urllib
import re
from dysms_python import demo_sms_send
import random
import pymysql
from labeling_tool import labeling_tool
# from get_goods_info.get_goods_info import get_goods_calss
from craw_taobaogoods.taobao_goods import craw_taobaogoods
from Selenium_Test import Selenium_Taobao
from django.contrib import messages
from multiprocessing.dummy import Pool
from competition_analysis.competition_analysis import Get_data
from category_thesaurus import category_thesaurus
# from crawd_portrait.crawd_portrait import Search_crowd_ortraits
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from store_anay.Category_composition import Category_composition
from store_anay.Service_indicator_data import Server_indicator_data
from store_anay.Shop_flow_analysis import Shop_flow_analysis
from store_anay.product_keyword_data import prodouct_keyword_data
from store_anay.product_data_analysis import prodouct_data_analysis
from store_anay.store_day_data import store_main
from crawd_portrait.crawd_portrait import PortraitCrowd

from forms import LoginForm, registerForm, taobaoLoginForm
from django.contrib.auth.hashers import make_password

from hot_words import hotWord
from data_json import data_json
from chetu import CheTu

from django.views import View

from taobao.extension import Link_database, OeratingSQL, CrowdPortraitSQL
from taobao.extension import TrafficSQL
from taobao.extension import ItemAnalysisSQL
from taobao.extension import ServiceIndicatorsSQL
from taobao.extension import ItemKeywordsSQL
from taobao.extension import DryCargoSQL
from taobao.extension import UpdateDrySQL
from taobao.extension import LikeSQL
from taobao.extension import Category_SQL
from taobao.extension import UserStatisticalSQL

from taobao.take_data import OeratingTake, Crowd_Portrait
from taobao.take_data import TrafficTake
from taobao.take_data import ItemAnalysis
from taobao.take_data import ServiceIndicators
from taobao.take_data import ItemKeywords
from taobao.take_data import SelectKey
from taobao.take_data import QueryBBS
from taobao.take_data import When_Month
from taobao.take_data import Before_Month
from taobao.take_data import Admin_after
from taobao.take_data import sel_user_statistical
from taobao.take_data import sel_due_to
from taobao.take_data import registered_time

from taobao.delete_data import del_data
from taobao.qiniu_link import storage
from taobao.month_date import dateAnay
from taobao.delete_data import del_category
from taobao.organization_data import after_data, crowd_portrait_place

import string
import math
from datetime import timedelta


# from dwebsocket import require_websocket,accept_websocket

# global L_uesr
# L_uesr = []

# def aaaa(request):
# 	if request.method == 'GET':
# 		return render(request, 'test_websocket.html')


# @accept_websocket
# def test_websockt(request):
# 	if request.is_websocket():
# 		# message = request.websocket.wait()
# 		for message in request.websocket:
# 			message = message.decode('utf-8')
# 			if message in L_uesr:
# 				status = 'Flase'
# 			else:
# 				L_uesr.append(message)
# 				status = 'True'
# 			request.websocket.send(status.encode('utf-8'))  # 发送消息到客户端
# 			print (L_uesr)
# 	elif request.method == 'GET':
# 		return JsonResponse({"result":'GET求情并非Websockt', "msg": "执行成功"})

# 权限


def permmsion_check(user_id, Required_level):
    now_time = time.time()
    # db = pymysql.connect(host='rm-m5ev2j6ywo4m51ebu5o.mysql.rds.aliyuncs.com', user='root', passwd='112358Ys', db='djt',
    # 					 charset='utf8')
    # cursor = db.cursor()
    db, cursor = Link_database()

    sql_select_vip_date = ''' SELECT auth_user.vip_date FROM auth_user WHERE id = %d ''' % (user_id)  # 查找用户VIP时间
    cursor.execute(sql_select_vip_date)
    try:
        vip_date = time.mktime(cursor.fetchone()[0].timetuple())
    except:
        vip_date = 0
    if vip_date >= now_time:
        sql_select_vip_level = ''' SELECT auth_user.vip_level FROM auth_user WHERE id = %d ''' % (user_id)  # 查找用户VIP等级
        cursor.execute(sql_select_vip_level)
        try:
            vip_level = int(cursor.fetchone()[0])
        except:
            vip_level = 0  # 没VIP等级数据
        if vip_level >= Required_level:
            return {"status": True, "result": [], "msg": 'OK'}
        else:
            return {"status": False, "result": '你目前的权限太低，请充值后再访问！', "msg": ''}
    else:  # 到期

        sql_select_join_date = ''' SELECT auth_user.date_joined FROM auth_user WHERE id = %d ''' % (
            user_id)  # 查找用户VIP时间
        cursor.execute(sql_select_join_date)
        join_date = time.mktime(cursor.fetchone()[0].timetuple())
        if now_time >= join_date + 86400 + 36000:  # 24小时，服务器时间差
            # 过期VIp等级改为0
            sql = """update auth_user set vip_level=0 where id=%d""" % user_id
            cursor.execute(sql)
            db.commit()
            cursor.close()
            db.close()
            return {"status": False, "result": '会员时间已到期，请充值后再使用！', "msg": ''}
        else:
            vip_level = 1
            if vip_level >= Required_level:
                return {"status": True, "result": [], "msg": 'OK'}
            else:
                return {"status": False, "result": '你目前的权限太低，请充值后再访问！', "msg": ''}


def hostname():
    """判断本地与服务器"""
    sys = os.name
    if sys == 'nt':
        hostname = os.getenv('computername')
        return hostname
    elif sys == 'posix':
        host = os.popen('echo $HOSTNAME')
        try:
            hostname = host.read()
            return hostname
        finally:
            host.close()
    else:
        return 'Unkwon hostname'


# SKU分析
@csrf_exempt
def sku_api(request):
    if request.method == "POST":
        try:
            Json_data = {}
            user = request.POST.get('user')
            goods_id = request.POST.get('goods_id')
            maxPage = int(request.POST.get('maxPage'))
            taobao = json.loads(request.POST.get('taobao'))
            is_Visit = permmsion_check(int(user), 1)

            if is_Visit['status'] == True:
                # proxies = {'http':request.POST.get('proxies')}
                # Sku.proxies = proxies
                try:
                    Json_data = SkuComent(goods_id, maxPage, taobao)
                    return JsonResponse({"status": True, "result": Json_data})
                except:
                    return JsonResponse({"status": False, "result": "请检查您的id是否复制或输入正确！"})
            else:
                return JsonResponse(is_Visit, status=200)
        except Exception as e:
            return JsonResponse({"status": False, "result": "系统繁忙，请稍候再试！", "msg": str(e)})


# 评价分析
# @csrf_exempt
# def comment_api(request):
# 	if request.method == "POST" :
# 		try:
# 			Json_data = {}
# 			url_info = request.POST['url']
# 			user = request.POST.get('user')
# 			is_Visit = permmsion_check(int(user),1)

# 			if is_Visit['status'] == True:
# 				# proxies = {'http':request.POST.get('proxies')}
# 				Comment = coments_info_class()
# 				# Comment.proxies = proxies
# 				try:
# 					Json_data = Comment.get_comments_info(url_info)
# 					if len(Json_data) == 0:
# 						return JsonResponse({"status":False, "result":"该商品没有评价！"})
# 					else:
# 						return JsonResponse({"status":True, "result":Json_data})
# 				except:
# 					return JsonResponse({"status":False, "result":"请检查您的链接是否复制或输入正确！"})
# 			else:
# 				return JsonResponse(is_Visit ,status=200)	
# 		except Exception as e:
# 			return JsonResponse({"status":False, "result":"系统繁忙，请稍候再试！", "msg":str(e)})


# # 店铺宝贝采集
# @csrf_exempt
# def goodsInfo_api(request):
# 	if request.method == "POST":
# 		try:
# 			Json_data = {}
# 			page_number = int(request.POST['pageNumber'])
# 			lowerPrice = request.POST.get('lowerPrice')
# 			hightPrice = request.POST.get('hightPrice')
# 			user = request.POST.get('user')
# 			is_Visit = permmsion_check(int(user), 1)

# 			if is_Visit['status'] == True:

# 				reserve_price = []
# 				reserve_price.append(lowerPrice)
# 				reserve_price.append(hightPrice)
# 				if reserve_price == [] or reserve_price == "":
# 					reserve_price = ['', '']

# 				key = request.POST['key']
# 				# 商品关键词为空时返回一条结果
# 				if len(key) == 0:
# 					return JsonResponse({'status': False, 'result': '商品关键词不可为空！'})

# 				sales_order = int(request.POST['select'])
# 				keywordList = [{'page_number': page_number, 'reserve_price': reserve_price, 'key': key,
# 								'sales_order': sales_order}]

# 				# keywordList = eval(request.POST['keyword_list'])

# 				GoodsInfo = get_goods_calss()
# 				GoodsInfo.data_list = keywordList
# 				Json_data = GoodsInfo.get_good_info()
# 				DataList = []
# 				for data in Json_data:
# 					for result in data:
# 						DataList.append(result)
# 				return JsonResponse({"status": True, "result": DataList})

# 			else:
# 				return JsonResponse(is_Visit, status=200)

# 		except Exception as e:
# 			return JsonResponse({"status": False, "result": "系统繁忙，请稍候再试", "msg": str(e)})


# 单品词根分析
def product_analysis_api(request):
    if request.method == 'POST':
        keyword = request.POST.get('keyword')
        user = request.POST.get('user')
        is_Visit = permmsion_check(int(user), 2)

        if is_Visit['status'] == True:
            if len(keyword) == 0:
                return JsonResponse({'status': False, 'result': '标题不可为空！'})

            try:
                result = craw_taobaogoods(keyword)
                if len(result) != 0:
                    return JsonResponse({'status': True, 'result': result})
            except Exception as e:
                return JsonResponse({'status': False, 'result': '请检查标题！', 'msg': str(e)})
        else:
            return JsonResponse(is_Visit, status=200)


# 关键词竞争度
@csrf_exempt
def competition_analysis_api(request):
    if request.method == "POST":
        Json_data = {}
        keyword = eval(request.POST.get('keyword'))
        reserve_price = eval(request.POST.get('reserve_price'))  # 价格区间对销量数据有影响 [50,100]
        taobao_cookies = eval(request.POST.get('taobao'))
        user = request.POST.get('user')
        is_Visit = permmsion_check(int(user), 2)

        if is_Visit['status'] == True:

            get_data = Get_data()
            get_data.get_cookie = taobao_cookies
            get_data.reserve_price = reserve_price
            pool = Pool(math.ceil(len(keyword) / 5))
            onlineGoods_list = pool.map(get_data.get_onlineGoods, keyword)
            # onlineShopper_list = pool.map(get_data.get_sale, keyword)
            try:
                onlineGoods_list[0]['code']
                pool.close()
                pool.join()
                return JsonResponse({"result": "淘宝登陆过期，请重新登陆！", "msg": "", "status": False}, status=200)

            except:
                pool.close()
                pool.join()
                return JsonResponse({"result": onlineGoods_list, "msg": "执行成功", "status": True}, status=200)

        else:
            return JsonResponse(is_Visit, status=200)


# 搜索人群画像
# @csrf_exempt
# def crawd_portrait_api(request):
# 	if request.method == 'POST':
# 		user = request.POST.get('user')
# 		is_Visit = permmsion_check(int(user), 2)

# 		if is_Visit['status'] == True:
# 			try:
# 				keyword = eval(request.POST.get('keyword'))
# 				proxies = {'http': '221.10.157.241:4212'}
# 				taobao = eval(request.POST.get('taobao'))
# 				time_interval = int(request.POST.get('time_interval'))

# 				crawData = Search_crowd_ortraits(keyword, time_interval, proxies, taobao)
# 				return JsonResponse({'status': True, 'result': crawData})
# 			except Exception as e:
# 				return JsonResponse({'status': False, 'result': '淘宝登录已过期，请重新登录！', 'msg': str(e)}, status=200)
# 		else:
# 			return JsonResponse(is_Visit, status=200)


@csrf_exempt
def test_api(request):
    if request.method == 'POST':
        url_info = request.POST.get('url')
        return JsonResponse({"result": {'type': url_info}, "msg": "执行成功"})


def InstanceCookies(instance):
    time.sleep(2)  # 等待登陆完成
    if str(instance.current_url).split('=')[
        0] == 'https://www.tmall.com/?ali_trackid' or instance.current_url == 'https://myseller.taobao.com/home.htm' or instance.current_url == 'https://mai.taobao.com/seller_admin.htm' or instance.current_url == 'https://subway.simba.taobao.com/#!/home' or instance.current_url == 'https://subway.simba.taobao.com/#!/novice-village/index':
        # if self.driver.current_url == 'https://subway.simba.taobao.com/#!/home':
        cookies_dic = {}
        cookies_list = instance.get_cookies()
        for i in cookies_list:
            cookies_dic[i["name"]] = i["value"]
        time.sleep(0.5)
        instance.quit()
        return cookies_dic
    else:
        instance.quit()
        raise


# 淘宝登陆API
selenium_dict = {}
selenium_taobao = Selenium_Taobao()


@csrf_exempt
def taobaologin_api(request):
    if request.method == 'POST':
        Type = request.POST.get('type')
        event_name = eval(request.POST.get('event_name'))
        username = request.POST.get('username')

        if Type == '1':
            # 返回登陆成功的cookies
            if event_name != None:
                event = selenium_dict[event_name]
                # try:
                taobao_cookies = InstanceCookies(event)
                del selenium_dict[event_name]  # 删除事件

                # db = pymysql.connect(host='rm-m5ev2j6ywo4m51ebu5o.mysql.rds.aliyuncs.com', user='root',
                #                      passwd='112358Ys', db='djt', charset='utf8')
                # cursor = db.cursor()
                db, cursor = Link_database()

                # 记录登陆时间
                now_time = datetime.datetime.now()
                fmt_time = now_time.strftime("%Y-%m-%d %H:%M:%S")
                updatesql = """ update auth_user set last_login_time = '%s' where username = '%s' """ % (
                    fmt_time, username)
                cursor.execute(updatesql)
                db.commit()

                # 增加用户登陆次数
                CheckName_Sql = """ select * from user_expand where user_name = '%s' """ % (username)
                cursor.execute(CheckName_Sql)
                if cursor.fetchone():
                    # 更改数量情况

                    Updata_Sql = """ UPDATE user_expand SET landing_times = landing_times + 1 """ % ()
                    cursor.execute(Updata_Sql)
                    db.commit()
                else:
                    # 新增设备
                    inset_sql = """ INSERT INTO  user_expand
					(user_name,landing_times) 
					VALUES ('%s',%d) """ % (username, 1)
                    cursor.execute(inset_sql)
                    db.commit()

                if taobao_cookies != None:
                    select_user = """ select a.username,b.taobao_account_name,b.user_id from auth_user a left join taobao_account b on a.id = b.user_id where a.username = '%s' """ % username
                    if cursor.execute(select_user) > 0:
                        try:
                            db_nickname = cursor.fetchone()[1]
                        except:
                            db_nickname = None

                        try:
                            nickname = taobao_cookies["sn"]
                        except:
                            nickname = taobao_cookies["tracknick"]

                        # nickname = track_nickname if track_nickname!="" else sn_nickname

                        # 新用户注册未绑定店铺时先让用户绑定
                        # print (db_nickname,'#########')
                        if db_nickname == None:
                            select_auth_user = """ select id from auth_user where username = '%s' """ % username
                            cursor.execute(select_auth_user)

                            user_id = cursor.fetchone()[0]

                            insert_taobao = """ insert into taobao_account(taobao_account_name,user_id) values('%s',%d) """ % (
                                nickname, user_id)
                            cursor.execute(insert_taobao)

                            db.commit()
                            return JsonResponse({'status': True, 'result': taobao_cookies, 'msg': '成功绑定！'})

                        # 已经绑定过店铺的用户在下一次登录时确认
                        elif db_nickname == nickname:
                            return JsonResponse({'status': True, 'result': taobao_cookies, 'msg': '登录成功！'})
                        # elif db_nickname == track_nickname:
                        # 	return JsonResponse({'status':True,'result':taobao_cookies,'msg':'登录成功！'})
                        else:
                            return JsonResponse({'status': False, 'result': '该淘宝店铺账号与软件账号对应不符合！'})
                else:
                    return JsonResponse({'status': False, 'result': '登陆失败'})

    # except:
    # 	return JsonResponse({'status':False,'result':'步骤错误，请先扫码'})


# 获取二维码连接
def qr_api(request):
    if request.method == 'POST':

        Type = request.POST.get('type')
        if Type == '0':
            selenium_instance = selenium_taobao.get_Qr()
            event_name = ''.join(random.sample(string.ascii_letters + string.digits, 8))
            selenium_dict[event_name] = selenium_instance['instance']  # 添加事件
            return JsonResponse({'status': True, 'msg': selenium_instance['qr'], 'event_name': event_name})


# 权限API
# @csrf_exempt
# def limits_user_api(request):
# 	if request.method == 'POST':
# 		username = request.POST.get('username')
# 		now_time = time.time()
# 		db = pymysql.connect(host='rm-m5ev2j6ywo4m51ebu5o.mysql.rds.aliyuncs.com',user='root',passwd='112358Ys',db='djt',charset='utf8')
# 		cursor = db.cursor()
# 		sql_select_vip_date = ''' SELECT auth_user.vip_date FROM auth_user WHERE username ='%s' ''' % (username)
# 		cursor.execute(sql_select_vip_date)
# 		try:
# 			vip_date = time.mktime(cursor.fetchone()[0].timetuple())
# 		except:
# 			vip_date = 0
# 		if vip_date >= now_time:
# 			return JsonResponse({'status':True})
# 		else:
# 			return JsonResponse({'status':False}) 


def dealWithData(data):
    user_list = []
    for i in data:
        user_set = {}
        user_set["userid"] = i[0]
        user_set["username"] = i[1]
        try:
            user_set["taobaoacount"] = taobaonick_to_cn(i[2])
        except:
            user_set["taobaoacount"] = False
        if i[3] == 0:
            user_set["isAdmin"] = False
        else:
            user_set["isAdmin"] = i[3]
        try:
            if i[4] != None:
                user_set["isVip"] = True
                user_set["viplevel"] = int(i[4])
            else:
                user_set["isVip"] = False
                user_set["viplevel"] = 1
        except:
            user_set["isVip"] = False
            user_set["viplevel"] = 0

        try:
            if i[5] == 1:
                user_set["isLogin"] = True
            else:
                user_set["isLogin"] = False
        except:
            user_set["isLogin"] = False
        user_list.append(user_set)

        if i[6] != None:
            user_set["vipdate"] = i[6].strftime("%Y-%m-%d")
        else:
            user_set["vipdate"] = ""

    return user_list


def taobaonick_to_cn(nickname):
    c = urllib.parse.unquote(nickname)
    zhPattern = re.compile(u'[\u4e00-\u9fa5]+')
    match = zhPattern.search(c)
    user_nick = ''
    if match:
        user_nick = c
    else:
        user_nick = c.encode('utf-8').decode('unicode_escape')
    return user_nick


# 登陆API
@csrf_exempt
def login_api(request):
    if request.method == 'POST':
        username = request.POST.get("username")
        password = request.POST.get("password")
        status = request.POST.get("type")

        # db = pymysql.connect(host='rm-m5ev2j6ywo4m51ebu5o.mysql.rds.aliyuncs.com', user='root', passwd='112358Ys',
        #                      db='djt', charset='utf8')
        # cursor = db.cursor()
        db, cursor = Link_database()

        if status == "0":
            user = authenticate(username=username, password=password)
            if user:
                # 先查询用户信息
                select_account_sql = """ select a.id, a.username, b.taobao_account_name, a.is_superuser, a.vip_level, a.isLogin from auth_user a LEFT JOIN taobao_account b on a.id = b.user_id where a.username = '%s' """ % username

                # 用户登录之后将登录状态改为1
                if cursor.execute(select_account_sql) == 1:
                    update_userStatus = """ update auth_user set isLogin = 1 where username = '%s' """ % username
                    cursor.execute(update_userStatus)
                    db.commit()

                    result_sql = """ select a.id, a.username, b.taobao_account_name, a.is_superuser, a.vip_level, a.isLogin, a.vip_date from auth_user a LEFT JOIN taobao_account b on a.id = b.user_id where a.username = '%s' """ % username
                    if cursor.execute(result_sql) == 1:
                        result = cursor.fetchall()
                        user_list = dealWithData(result)
                        return JsonResponse({'status': True, 'result': user_list})
            else:
                return JsonResponse({'status': False, 'result': "该账号不存在或密码错误！"})


# 注册API
sms_code_dict = {}


@csrf_exempt
def register_api(request):
    if request.method == 'POST':
        work_type = request.POST.get('type')
        sms_code = ''
        if work_type == '0':
            # 发送验证码
            phone = request.POST.get('phone')

            # 产生一个随机码
            while (len(sms_code) < 6):
                x = str(random.randint(1, 9))
                sms_code = sms_code + x

            # 验证码缓存在内存中
            code_event_name = ''.join(random.sample(string.ascii_letters + string.digits, 8))
            sms_code_dict[code_event_name] = sms_code

            # 阿里云短信服务
            params = '{"code":%s,"product":"ydsp"}' % (sms_code)
            json_code = json.loads(
                str((demo_sms_send.send_sms(phone, "点将台", "SMS_136160553", params)), encoding='utf-8'))
            if json_code['Code'] == 'OK':
                return JsonResponse({'status': True, 'result': "正在获取验证码...", 'code_event_name': code_event_name})
            else:
                msg = '你的手机号' + json_code['Message'] + '请稍后注册'
                return JsonResponse({'status': False, 'result': msg})
        elif work_type == '1':
            # 去注册
            username = request.POST.get('username')
            phone = request.POST.get('phone')
            user_qq = request.POST.get('user_qq')
            user_wx = request.POST.get('user_wx')
            # print(user_wx)
            password = request.POST.get('password')
            code = request.POST.get('testcode')
            code_event_name = eval(request.POST.get('code_event_name'))

            # db = pymysql.connect(host='rm-m5ev2j6ywo4m51ebu5o.mysql.rds.aliyuncs.com', user='root', passwd='112358Ys',
            #                      db='djt', charset='utf8')
            # cursor = db.cursor()

            db, cursor = Link_database()

            select_sql = """select * from auth_user where username='%s' or first_name='%s'""" % (username, phone)
            if cursor.execute(select_sql) == 0:

                try:
                    sms_code = sms_code_dict[code_event_name]
                    del sms_code_dict[code_event_name]  # 清除内存数据
                except:
                    return JsonResponse({'status': False, 'result': '请先获取验证码!'})

                if code == sms_code:
                    # 生成用户
                    user = User.objects.create_user(username=username, password=password, first_name=phone)
                    user.save()

                    # 插入user_qq,user_wx
                    update_userStatus = """ update auth_user set user_qq = '%s',user_wx ='%s' where username = '%s' """ % (
                        user_qq, user_wx, username)
                    cursor.execute(update_userStatus)
                    db.commit()

                    # 注册成功则返回用户的初始登录状态，以及自动登录
                    select_account_sql = """ select a.id, a.username, b.taobao_account_name, a.is_superuser, a.vip_level, a.isLogin, a.vip_date from auth_user a LEFT JOIN taobao_account b on a.id = b.user_id where a.username = '%s' """ % username

                    # 自动登录
                    if cursor.execute(select_account_sql) == 1:

                        update_userStatus_sql = """ update auth_user set isLogin = 1 where username = '%s' """ % username
                        cursor.execute(update_userStatus_sql)
                        db.commit()

                        result_sql = """ select a.id, a.username, b.taobao_account_name, a.is_superuser, a.vip_level, a.isLogin ,a.vip_date from auth_user a LEFT JOIN taobao_account b on a.id = b.user_id where a.username = '%s' """ % username
                        if cursor.execute(result_sql) == 1:
                            result = cursor.fetchall()
                            user_list = dealWithData(result)
                            return JsonResponse({'status': True, 'result': user_list})

                    else:
                        return JsonResponse({'status': False, 'result': '用户名不正确！'})
                else:
                    return JsonResponse({'status': False, 'result': '验证码错误！'})
            else:
                return JsonResponse({'status': False, 'result': '该名称已被注册或手机号以被注册!'})


# 修改密码API
@csrf_exempt
def update_api(request):
    if request.method == 'POST':
        work_type = request.POST.get('type')
        phone = request.POST.get('phone')
        if work_type == "0":
            sms_code = ''
            while (len(sms_code) < 6):
                x = str(random.randint(1, 9))
                sms_code = sms_code + x

            # 验证码缓存在内存中
            code_event_name = ''.join(random.sample(string.ascii_letters + string.digits, 8))
            sms_code_dict[code_event_name] = sms_code

            # 阿里云短信服务
            params = '{"code":%s,"product":"ydsp"}' % (sms_code)
            json_code = json.loads(
                str((demo_sms_send.send_sms(phone, "点将台", "SMS_136160553", params)), encoding='utf-8'))
            # print (json_code)
            if json_code['Code'] == 'OK':
                return JsonResponse({'status': True, 'result': "正在获取验证码...", "code_event_name": code_event_name})

            else:
                msg = '你的手机号' + json_code['Message'] + '请稍后修改'
                return JsonResponse({'status': False, 'result': msg})

        elif work_type == "1":
            try:
                username = request.POST.get('username')
                password = request.POST.get('password')
                code = request.POST.get('code')
                code_event_name = eval(request.POST.get('code_event_name'))

                try:
                    sms_code = sms_code_dict[code_event_name]
                    del sms_code_dict[code_event_name]  # 清除内存数据
                except:
                    return JsonResponse({'status': False, 'result': '请先获取验证码！'})

                if str(sms_code) == code:
                    # db = pymysql.connect(host='rm-m5ev2j6ywo4m51ebu5o.mysql.rds.aliyuncs.com', user='root',
                    #                      passwd='112358Ys', db='djt', charset='utf8')
                    # cursor = db.cursor()
                    db, cursor = Link_database()
                    select_sql = '''select * from auth_user where username = '%s' and first_name = '%s' ''' % (
                        username, phone)
                    if cursor.execute(select_sql) == 1:
                        cknewpassword = make_password(password, None, 'pbkdf2_sha256')
                        user = User.objects.filter(username=username).update(password=cknewpassword)

                        db.commit()

                        select_account_sql = """ select a.id, a.username, b.taobao_account_name, a.is_superuser, a.vip_level, a.isLogin ,a.vip_date from auth_user a LEFT JOIN taobao_account b on a.id = b.user_id where a.username = '%s' """ % username
                        cursor.execute(select_account_sql)

                        result = cursor.fetchall()
                        user_list = dealWithData(result)

                        return JsonResponse({'status': True, 'result': user_list})
                    else:
                        return JsonResponse({'status': False, 'result': '与注册手机号码不一致！'})
                else:
                    return JsonResponse({'status': False, 'result': '验证码不正确！'})
            # user = User.objects.create_user(username=username,password=password)
            # user.save()
            except Exception as e:
                return JsonResponse({'status': False, 'message': str(e)})


# 类目构成
@csrf_exempt
def Category_composition_api(request):
    if request.method == 'POST':
        user = request.POST.get('user')
        is_Visit = permmsion_check(int(user), 3)

        if is_Visit['status'] == True:
            try:
                category_composition = Category_composition()
                category_composition.cookies = json.loads(request.POST.get('taobao'))
                mon_time = json.loads(request.POST.get('time'))
                category_composition.dateRange = str(mon_time['start']) + "|" + str(mon_time['end'])  # 每个月头月末
                fat = category_composition.Category()

                # 处理子类数据
                cateIList = []
                for i in fat['data']['levelOneCategoryBOList']:
                    time.sleep(0.5)
                    for h in (category_composition.Category_son(i['cateId'])):
                        h['fname'] = i['cateName']
                        cateIList.append(h)
                return JsonResponse({'status': True, 'result': cateIList})
            except:
                return JsonResponse({'status': False, 'result': '淘宝未登录或登陆过期'})
        else:
            return JsonResponse(is_Visit, status=200)


# # 服务指标数据
# @csrf_exempt
# def serviceIndicator_api(request):
# 	if request.method == 'POST':
# 		try:
# 			service = Server_indicator_data()
# 			service.cookies = json.loads(request.POST.get('taobaoCookie'))
# 			# print("淘宝cookie:", service.cookies)
# 			# work_time = {"start": "2018-07-01", "end": "2018-07-30"}
# 			res = service.get_server_data()
# 			try:
# 				message = res[0]["message"]# 判断该子账号的权限状态
# 			except:
# 				message = res[0]["msg"]

# 			serviceList = []
# 			if message == "操作成功":
# 				for i in res:
# 					serviceList.append(i)
# 				return JsonResponse({'status':True, 'result':serviceList})
# 			elif message == "You must login system first.":
# 				msg = "淘宝登录已过期，需要重新登录哦！"
# 				return JsonResponse({'status': True, 'result': msg})
# 			elif message == "No Main Auth Func Permission ,sycm_server.":# 该店铺账号在生意参谋---"服务"没有访问权限
# 				msg = "亲，您暂时没有该模块的访问权限，需要由主账号或者有超级管理员权限的子账号到 子账号管理-员工管理 中修改岗位权限，开通 “生意参谋单店版服务洞察” 功能。"
# 				return JsonResponse({'status':False, 'result':msg})
# 		except:
# 			result = "淘宝未登录！"
# 			return JsonResponse({'status':False, 'result':result})

# # 店铺流量分析
# @csrf_exempt
# def shop_flow_analysis_api(request):
# 	if request.method == 'POST':
# 		try:
# 			shop_flow = Shop_flow_analysis()
# 			shop_flow.cookies = json.loads(request.POST.get('taobao'))
# 			shop_flow.dateRange = json.loads(request.POST.get('dataRange'))

# 			try:
# 				show_flow_data = shop_flow.resp_all_data()
# 				return JsonResponse({'status':True, 'result': show_flow_data})
# 			except Exception as e:
# 				return JsonResponse({'status':False, 'result':'系统繁忙，请稍候再试', 'message':str(e)})
# 		except:
# 			msg = "淘宝登录已过期，需要重新登录哦！"
# 			return JsonResponse({'status':False, 'result':msg})

# # 单品关键词数据
# @csrf_exempt
# def productItem_keyword_data_api(request):
# 	if request.method == 'POST':
# 		try:
# 			product_item = prodouct_keyword_data()
# 			try:
# 				product_item.itemId = json.loads(request.POST.get('itemId'))
# 			except:
# 				return JsonResponse({'status':False, 'result':'您的ID有误'})

# 			product_item.dateRange = json.loads(request.POST.get('dateRange'))
# 			product_item.cookies = json.loads(request.POST.get('taobao'))
# 			# if product_item.itemId == "" or product_item.itemId == None:#用户不输入商品ID时返回一个错误提示
# 			# 	empMsg = "您的商品ID不可为空，请输入！"
# 			# 	return JsonResponse({'status':False, 'result':empMsg})
# 			# else:
# 			try:
# 				productData = product_item.get_day_data()
# 				return JsonResponse({'status':True, 'result':productData})
# 			except:
# 				errMsg = "请检查您的店铺是否有这款商品的ID。"
# 				return JsonResponse({'status':False, 'result':errMsg})
# 		except Exception as e:
# 			print(e)
# 			msg = "淘宝未登录或登录过期，需要重新登录哦！"
# 			return JsonResponse({'status':False, 'result':msg})

# # 单品数据分析
# @csrf_exempt
# def product_data_analysis_api(request):
# 	if request.method == 'POST':
# 		try:
# 			product_analysis = prodouct_data_analysis()
# 			try:
# 				product_analysis.dateRange = json.loads(request.POST.get('dateRange'))
# 			except:
# 				return JsonResponse({'status':False, 'result':'日期有误，请重试！'})

# 			product_analysis.cookies = json.loads(request.POST.get('taobao'))

# 			try:
# 				productData = product_analysis.main()
# 				return JsonResponse({'status':True, 'result':productData})
# 			except Exception as e:
# 				errMsg = "系统繁忙，请稍候再试！"
# 				return JsonResponse({'status':False, 'result':errMsg, 'message':e})
# 		except Exception as e:
# 			print(e)
# 			msg = "淘宝未登录或登录过期，需要重新登录哦！"
# 			return JsonResponse({'status':False, 'result':msg})

# # 每日运营数据
# @csrf_exempt
# def daily_operational_data_api(request):
# 	if request.method == 'POST':
# 		try:
# 			cookies = json.loads(request.POST.get('taobao'))
# 			try:
# 				storeData = store_main(cookies)
# 				return JsonResponse({'status':True, 'result':storeData})
# 			except Exception as e:
# 				errMsg = "您的店铺没有该权限！"
# 				return JsonResponse({'status':False, 'result':errMsg, 'message':str(e)})
# 		except Exception as e:
# 			msg = "淘宝未登录或登录过期，需要重新登录哦！"
# 			return JsonResponse({'status':False, 'result':msg, 'message':str(e)})


# 类目词库分析
def category_thesaurus_api(request):
    if request.method == 'POST':
        keyword = eval(request.POST.get('keyword'))  # 文件所有关键词list
        taobao = eval(request.POST.get('taobao'))
        user = request.POST.get('user')

        is_Visit = permmsion_check(int(user), 2)

        if is_Visit['status'] == True:

            data = category_thesaurus.Get_data()
            data.cookies = taobao

            pool = Pool(math.ceil(len(keyword) / 5))
            try:
                # 在线商品数
                cate_onlineGoodsData = pool.map(data.get_onlineGoods, keyword)
                L = []
                for i in cate_onlineGoodsData:
                    for k in i:
                        L.append(str(k))
                L1 = []
                for s in set(L):
                    L1.append(eval(s))

                M = []
                for s in range(0, len(L1), 500):
                    M.append(L1[s:s + 500])

            # print (cate_onlineGoodsData)
            # cate_onlineGoodsSet = {}
            # onlineGoodsIndex = 0
            # for item in cate_onlineGoodsData:
            #   cate_onlineGoodsSet[keyword[onlineGoodsIndex]] = item
            #   onlineGoodsIndex += 1

            # 销量
            # cate_salesData = pool.map(data.get_sale, keyword)
            # cate_salesSet = {}
            # salesIndex = 0
            # for item in cate_salesData:
            #   cate_salesSet[keyword[salesIndex]] = item
            #   salesIndex += 1

            except Exception as e:
                # cateData = []
                return JsonResponse({"status": False, "result": "淘宝未登录或登录已过期，请重新登录！", "msg": str(e)})

            pool.close()
            pool.join()

            # jsonData = {"onlineGoods":cate_onlineGoodsData}

            return JsonResponse({"status": True, "result": M})
        else:
            return JsonResponse(is_Visit, status=200)


# 行业热词榜
@csrf_exempt
def hot_words_api(request):
    if request.method == "POST":

        user = request.POST.get('user')
        is_Visit = permmsion_check(int(user), 1)

        if is_Visit['status'] == True:
            status = request.POST.get("type")
            hWords = hotWord.newTaobao()
            hWords.cookies = eval(request.POST.get("taobao"))

            # 获取所有类目
            if status == "0":
                try:
                    cateData = hWords.Category()
                    if cateData["code"] == 5810:
                        return JsonResponse({"status": False, "result": "淘宝登录信息已过期，请重新登录淘宝！", "msg": cateData["msg"]})
                    else:
                        return JsonResponse({"status": True, "result": cateData})
                # cateList = []
                # for item in cateData["data"]:
                # 	cateSet = {}
                # 	cateSet["parent_cateid"] = item[0]
                # 	cateSet["selected_cateid"] = item[1]
                # 	cateSet["catename"] = item[2]
                # 	cateSet["version"] = item[4]
                # 	cateSet["firstlevel_cateid"] = item[6]
                # 	cateSet["mainlevel_catename"] = item[7]
                #
                # 	cateList.append(cateSet)
                except Exception as e:
                    return JsonResponse({"status": False, "result": "系统繁忙，请稍候再试！", "msg": str(e)})

            elif status == "1":
                cateID = request.POST.get("cateid")
                time_interval = int(request.POST.get("time_interval"))
                searchWords = hWords.hotWord(cateID, time_interval)
                # 长尾词
                longWords = hWords.tailWord(cateID, time_interval)
                # 品牌词
                brandWords = hWords.brandWord(cateID, time_interval)
                # 核心词
                coreWords = hWords.coreWord(cateID, time_interval)
                # 修饰词
                modifyWords = hWords.attrWord(cateID, time_interval)
                words_set = {
                    "search": searchWords["data"],
                    "longtail": longWords["data"],
                    "brand": brandWords["data"],
                    "core": coreWords["data"],
                    "modify": modifyWords["data"]
                }
                return JsonResponse({'status': True, 'result': words_set})
        else:
            return JsonResponse(is_Visit, status=200)


# 地域分析
@csrf_exempt
def geographic_api(request):
    if request.method == "POST":
        user = request.POST.get('user')
        is_Visit = permmsion_check(int(user), 2)

        if is_Visit['status'] == True:
            # 所有城市列表
            city_list = []
            # 所有省份列表
            province_list = []
            # 省份所有订单数统计
            analysis_province = []
            # 城市所有订单数统计
            analysis_city = []
            # 去重省份城市
            province_city = []
            # 每个省份下的城市
            province_city_dict = {}

            # 数据处理
            file = request.POST.get("file")
            file = json.loads(file)
            summary = 0
            for area in file:
                summary += 1
                province_list.append(area["province"])
                city_list.append(area["city"])
                if area not in province_city:
                    province_city.append(area)

            analysis_city = dict(Counter(city_list) + Counter(analysis_city))
            analysis_province = dict(Counter(province_list) + Counter(analysis_province))
            for prov in set(province_list):
                if prov not in province_city_dict:
                    province_city_dict[prov] = []
                    for i in province_city:
                        if prov == i['province']:
                            province_city_dict[prov].append(i["city"])

            return JsonResponse({"province_city_dict": province_city_dict, "analysis_city": analysis_city,
                                 "analysis_province": analysis_province, "summary": summary})
        else:
            return JsonResponse(is_Visit, status=200)


# 店铺诊断数据
@csrf_exempt
def store_diagnosis_api(request):
    if request.method == "POST":
        work_type = request.POST.get('type')
        if work_type == '0':
            try:
                name = request.POST.get('username')
                phone = request.POST.get('phone')
                taobaoNick = request.POST.get('nickname')
                taobaoPsw = request.POST.get('password')
                store_data = {
                    "name": name,
                    "tel": phone,
                    "taobaoNick": taobaoNick,
                    "taobaoPsw": taobaoPsw,
                    "is_visit": False
                }

                # print (name,tel,taobaoNick,taobaoPsw)
                store = data_json.store_Json_file()

                store.add_data(store_data)
                msg = "成功提交！"
                return JsonResponse({"status": True, "result": msg})
            except Exception as e:
                return JsonResponse({"status": False, "result": "系统繁忙，请稍候再试！", "msg": str(e)})
        elif work_type == '1':  #
            id = int(request.POST.get('id'))
            store = data_json.store_Json_file()
            result = store.update_data(id)
            return JsonResponse({"status": True, "result": result})


def chetu_api(request):
    ''' 车图 '''

    if request.method == "POST":
        page_number = int(request.POST.get('page_number'))
        keyword = request.POST.get('keyword')
        search_info = {"keyword": keyword, "pagenumber": page_number}
        return JsonResponse(CheTu.CheTu(search_info))  # 所有的判断都在爬虫里面


class OeratingView(View):
    """
    运营数据视图
    """

    def post(self, request):
        # 获取参数
        user_id_str = request.POST.get('user')
        store_name = request.POST.get('store')
        start_str = request.POST.get('start')
        check_str = request.POST.get('check')
        cookie_str = request.POST.get('taobao')
        user = request.POST.get('user')
        is_Visit = permmsion_check(int(user), 3)

        if is_Visit['status'] == True:

            try:
                # 判断参数
                user_id = int(user_id_str)
                start = int(time.mktime(time.strptime(start_str, '%Y-%m-%d')))
                check = int(time.mktime(time.strptime(check_str, '%Y-%m-%d')))
                cookie = eval(cookie_str)
            except Exception as e:
                return JsonResponse({"status": False, 'result': '参数错误'})

            now_date = int(
                time.mktime(time.strptime(datetime.datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d'))) - 86400  # 当前时间
            con, obj = Link_database()  # 链接数据库

            obj.execute("""select statDate from operating where statDate=%d and user=%d and store_name='%s'""" % (
                now_date, user_id, store_name))  # 查询最新数据是否存在
            if not obj.fetchone():
                obj.execute(
                    """select statDate from operating where user=%d and store_name='%s' order by statDate desc limit 1""" % (
                        user_id, store_name))  # 查询数据库中最新数据时间
                time_tuple = obj.fetchone()
                if not time_tuple:
                    storage_time = 0  # 数据库中无数据时，给定以个时间
                else:
                    storage_time = time_tuple[0]  # 数据库中最新数据时间

                data = []
                # try:
                resp = store_main(cookie)
                print(resp)
                # except Exception as e:
                #     return JsonResponse({"status": False, 'result': '爬虫服务器异常'})

                try:
                    if type(resp) == dict:
                        # 判断cookie
                        if resp['msg'] == '淘宝登陆过期':
                            return JsonResponse({"status": False, 'result': '淘宝登录失效'})
                        elif resp['data']['code'] == 5924:
                            return JsonResponse({"status": False,
                                                 'result': '亲，您暂时没有该模块的访问权限，需要由主账号或者有超级管理员权限的子账号到 子账号管理-员工管理 中修改岗位权限，开通 “生意参谋单店版服务洞察” 功能。'})
                # elif resp['code'] == 1003:
                #     return JsonResponse({"status": False, 'result': '数据正在更新，请稍后再试'})
                except Exception as e:
                    pass

                try:
                    if resp['code'] == 1003:
                        return JsonResponse({"status": False, 'result': '生意参谋数据正在更新，请稍后再试'})
                except Exception as e:
                    pass

                try:
                    for i in resp:
                        statdate = int(time.mktime(time.strptime(i['statDate'], '%Y-%m-%d')))
                        if statdate > storage_time:
                            data.append(i)
                except Exception as e:
                    return JsonResponse({"status": False, 'result': '爬虫数据异常'})
                # print(data)

                if data:
                    try:
                        # 调用数据库存储函数，存储数据
                        OeratingSQL(data, user_id, store_name)
                    except Exception as e:
                        return JsonResponse({"status": False, 'result': '数据存储失败'})

            try:
                # 查询数据
                query_data = OeratingTake(user_id, store_name, start, check)
            except Exception as e:
                return JsonResponse({"status": False, 'result': '数据读取失败'})

            obj.close()
            con.close()

            result = []
            for i in query_data:
                re = {}
                re['statDate'] = time.strftime('%Y-%m-%d', time.localtime(i[0]))
                re['store_product_cou'] = i[1]
                re['payItemcun'] = i[2]
                re['browse_number'] = i[3]
                re['visitors'] = i[4]
                re['payment'] = i[5]
                re['paymentRate'] = i[6]
                re['successful_refund'] = i[7]
                re['buyers'] = i[8]
                re['old_buyers'] = i[9]
                re['Unit_price'] = i[10]
                re['payment_Number'] = i[11]
                re['add_pay_number'] = i[12]
                re['Refund'] = i[13]
                re['Item_cnt'] = i[14]

                result.append(re)

            if ((check - start) / 86400 + 1) == len(result):
                return JsonResponse({'status': True, 'result': result})
            else:
                return JsonResponse({'status': True, 'result': result})
        else:
            return JsonResponse(is_Visit, status=200)


class TrafficView(View):
    """
    店铺流量分析视图
    """

    def post(self, request):
        # 获取参数
        user = request.POST.get('user')
        store_name = request.POST.get('store')
        start = request.POST.get('start')
        check = request.POST.get('check')
        cookie_str = request.POST.get('taobao')
        source = request.POST.get('source')

        user = request.POST.get('user')
        is_Visit = permmsion_check(int(user), 3)

        if is_Visit['status'] == True:
            try:
                # 判断参数
                user_id = int(user)
                cookie = eval(cookie_str)
            # print(cookie)
            except Exception as e:
                return JsonResponse({"status": False, 'result': '参数错误'})

            now_date = int(time.mktime(
                time.strptime(datetime.datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d'))) - 86400  # 前两天天时间,时间戳
            con, obj = Link_database()  # 链接数据库
            result = {}  # 最终数据格式
            state = ''  # 提示

            obj.execute("""select statDate from traffic where statdate=%d and user=%d and store_name='%s'""" % (
                now_date, user_id, store_name))  # 查询前一天天数据
            if not obj.fetchone():
                # if 1:
                obj.execute(
                    """select statDate from traffic where user=%d and store_name='%s' order by statDate desc limit 1""" % (
                        user_id, store_name))  # 查询数据库中最新数据
                time_tuple = obj.fetchone()
                if not time_tuple:
                    crawler_check = time.strftime('%Y-%m-%d', time.localtime(now_date - 86400 * 29))  # 新用户时默认爬去三十天数据
                else:
                    storage_time = time_tuple[0]
                    difference = (now_date - storage_time) // 86400
                    if difference > 30:
                        crawler_check = time.strftime('%Y-%m-%d', time.localtime(now_date - 86400 * 29))
                    else:
                        crawler_check = time.strftime('%Y-%m-%d', time.localtime(storage_time + 86400))

                try:
                    # 调用爬虫，爬取数据
                    flow = Shop_flow_analysis()
                    now_date_str = time.strftime('%Y-%m-%d', time.localtime(now_date))
                    # print(crawler_check)
                    # print(now_date_str)
                    flow.dateRange = {"start": crawler_check, "end": now_date_str}
                    # flow.dateRange = {"start": '2018-10-26', "end": '2018-10-26'}
                    flow.cookies = cookie
                    try:
                        data = flow.Any_day_data(flow.dateRange)
                    # print(data)
                    except Exception as e:
                        return JsonResponse({"status": False, 'result': '爬取数据失败', 'e': e})

                    # 判断爬虫cookie 是否失效
                    try:
                        if data[0]['code'] == 5810:
                            return JsonResponse({"status": False, 'result': '淘宝登录过期'})
                        for c in data:
                            if type(c) == dict:
                                if c['code'] == 1003:
                                    del data[data.index(c)]
                                    state = '%s 生意参谋数据正在更新，请稍后再试' % now_date_str
                        # return JsonResponse({"status": False, 'result': '生意参谋数据正在更新，请稍后再试'})
                    except Exception as e:
                        pass
                except Exception as e:
                    return JsonResponse({"status": False, 'result': '爬取服务器异常', 'e': e})

                try:
                    obj.execute("""select statDate from traffic where statdate=%d and user=%d and store_name='%s'""" % (
                        now_date, user_id, store_name))
                    if not obj.fetchall():
                        # 调用数据库存储函数，存储数据
                        TrafficSQL(data, user_id, store_name)
                except Exception as e:
                    return JsonResponse({"status": False, 'result': '数据存储失败', 'e': e})

            try:
                # 查询数据
                start_int = int(time.mktime(time.strptime(start, '%Y-%m-%d')))
                check_int = int(time.mktime(time.strptime(check, '%Y-%m-%d')))

                DP_obiect = TrafficTake(user_id, store_name, start_int, check_int, source)  # 实例查询类
                map_WX_data = DP_obiect.select_data()  # map 无线数据
                table_wx_data = DP_obiect.WX_table_data()  # table 无线数据
                table_pc_data = DP_obiect.PC_table_data()  # table pc数据
                DP_obiect.the_end()  # 关闭数据库连接，游标
            except Exception as e:
                return JsonResponse({"status": False, 'result': '数据读取失败'})

            obj.close()
            con.close()
            try:
                map = []
                # i = 0
                # while i < len(map_WX_data):
                #     day_list = []
                #     for a in map_WX_data[i:i + 10]:
                #         article_dict = {
                #             "WX": {"statDate": {"value": time.strftime('%Y-%m-%d', time.localtime(int(a[2])))},
                #                    "pageName": a[3],
                #                    "uv": {"value": a[4], "cycleCrc": a[5]},
                #                    "crtByrCnt": {"value": a[6], "cycleCrc": a[7]},
                #                    "crtRate": {"value": a[8], "cycleCrc": a[9]}
                #                    }
                #         }
                #         day_list.append(article_dict)
                #     map.append(day_list)
                #     i += 10
                for a in map_WX_data:
                    day_list = []
                    pricevalue = 0
                    if a[2] and a[6]:
                        pricevalue = a[6] / a[2] * a[5]
                    article_dict = {
                        "WX": {"statDate": {"value": time.strftime('%Y-%m-%d', time.localtime(int(a[0])))},
                               "pageName": a[1],
                               "uv": {"value": a[2]},
                               "crtByrCnt": {"value": a[3]},
                               "crtRate": {"value": round(a[4], 4)},
                               "priceValue": {"value": round(pricevalue, 4)}
                               }
                    }

                    day_list.append(article_dict)
                    map.append(day_list)

                table = {}  # table表 字典格式
                wx_data = []  # table wx数据
                for i in table_wx_data:
                    pricevalue = 0
                    if i[1] and i[4]:
                        pricevalue = float(i[4] / i[1]) * i[3]
                    day_wx_data = {
                        "pageName": i[0],
                        "uv": {"value": i[1]},
                        "crtByrCnt": {"value": i[2]},
                        "crtRate": {"value": round(i[2] / i[1], 4)},
                        "priceValue": {"value": round(pricevalue * i[3], 4)}
                    }
                    wx_data.append(day_wx_data)

                pc_data = []  # table pc数据
                for i in table_pc_data:
                    pricevalue = 0
                    if i[1] and i[4]:
                        pricevalue = float(i[4] / i[1]) * i[3]
                    day_pc_data = {
                        "pageName": i[0],
                        "uv": {"value": i[1]},
                        "crtByrCnt": {"value": i[2]},
                        "crtRate": {"value": round(i[2] / i[1], 4)},
                        "priceValue": {"value": round(pricevalue, 4)}
                    }
                    pc_data.append(day_pc_data)

                table['WX'] = {'data': wx_data}
                table['PC'] = {'data': pc_data}

                result['map'] = map
                result['table'] = table
            except Exception as e:
                return JsonResponse({"status": False, 'result': '数据读取有误'})

            date = (check_int - start_int) // 86400 + 1
            # print(date)
            # print(len(map_WX_data))

            if date == len(map_WX_data):
                return JsonResponse({'status': True, 'result': result, 'state': state}, status=200)
            else:
                return JsonResponse({'status': True, 'result': result, 'state': state}, status=200)
        else:
            return JsonResponse(is_Visit, status=200)


class ItemKeywordsView(View):
    """单品关键词数据视图"""

    def post(self, request):
        # 获取参数
        user_str = request.POST.get('user')
        store_name = request.POST.get('store')
        start_str = request.POST.get('start')
        check_str = request.POST.get('check')
        cookie_str = request.POST.get('taobao')
        goods_str = request.POST.get('goods')
        user = request.POST.get('user')
        is_Visit = permmsion_check(int(user), 3)

        if is_Visit['status'] == True:

            # 判断参数
            try:
                # 判断参数
                user_id = int(user_str)
                goods_id = int(goods_str)
                start = int(time.mktime(time.strptime(start_str, '%Y-%m-%d')))  # 起始时间戳
                check = int(time.mktime(time.strptime(check_str, '%Y-%m-%d')))  # 结束时间戳
                cookie = eval(cookie_str)
            except Exception as e:
                return JsonResponse({"status": False, 'result': '参数错误'})

            instance_obj = ItemKeywords(user_id, store_name, start, check, goods_id)  # 实例查询类

            # try:
            #     # 查询关系表
            #     bools = instance_obj.select_goods_id()  # 查询商品
            #     # print(bools)
            #     if not bools:
            #         num_tuple = instance_obj.select_associatcd_num()  # 查询商品id 数量
            #         # print(num_tuple)
            #         if num_tuple:
            #             if num_tuple[1] >= 3:
            #                 return JsonResponse({"status": False, 'result': '亲，你的账号只能绑定三个商品'})
            #             else:
            #                 instance_obj.save_associatcd_table()  # 保存
            #         else:
            #             instance_obj.save_associatcd_table()  # 保存
            # except Exception as e:
            #     return JsonResponse({"status": False, 'result': '关联表失败'})

            # 查询关键词业务逻辑
            now_date = int(time.mktime(time.strptime(datetime.datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d'))) - 86400
            new_time = time.strftime('%Y-%m-%d', time.localtime(now_date))
            # print(new_time)
            con, obj = Link_database()
            result = []  # 最终数据结构
            state = ''  # 提示

            select_goods_id_sql = """select id from item_associated where user_id=%d and goods_id=%d""" % (
                user_id, goods_id)
            obj.execute(select_goods_id_sql)
            if not obj.fetchone():
                return JsonResponse({"status": False, 'result': '商品id：%d 错误' % goods_id})

            obj.execute(
                """select statDate from test_itemkeywords where statdate=%d and user=%d and store_name='%s' and goods_id=%d""" % (
                    now_date, user_id, store_name, goods_id))  # 查询前一天数据
            if not obj.fetchone():
                # if 1:
                obj.execute(
                    """select statDate from test_itemkeywords where user=%d and store_name='%s' and goods_id=%d order by statdate desc limit 1""" % (
                        user_id, store_name, goods_id))  # 查询数据库中最新一条数据时间
                time_tuple = obj.fetchone()
                # 判断是否是新用户
                if not time_tuple:
                    storage_time = 0
                # crawler_check = time.strftime('%Y-%m-%d', time.localtime(now_date - 86400 * 29))  # 新用户时默认爬去三十天数据
                else:
                    storage_time = time_tuple[0]

                try:
                    # 调取爬虫
                    # now_date_str = time.strftime('%Y-%m-%d', time.localtime(now_date))
                    flow = prodouct_keyword_data()  # 爬虫对象
                    flow.itemId = goods_str

                    i = 1
                    now_date_1 = int(
                        time.mktime(time.strptime(datetime.datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d'))) - 86400
                    while i <= (now_date - int(storage_time)) // 86400 and i <= 30:
                        # print('111')
                        new_time = time.strftime('%Y-%m-%d', time.localtime(now_date_1))
                        # print(new_time)
                        flow.dateRange = {'start_time': new_time, 'end_time': new_time}
                        # flow.dateRange = {'start_time': '2018-10-26', 'end_time': '2018-10-26'}
                        flow.cookies = cookie
                        try:
                            data = flow.Any_day_data(flow.dateRange)
                        # print(data)
                        except Exception as e:
                            return JsonResponse({"status": False, 'result': '爬取数据失败'})

                        try:
                            # 检查cookie，权限
                            if data['code'] == 1100:
                                # instance_obj.delete_goods_id()  # 删除 goods_id
                                return JsonResponse({"status": False, 'result': '商品id：%d 错误,' % goods_id})
                            elif data['code'] == 5810:
                                # instance_obj.delete_goods_id()  # 删除 goods_id
                                return JsonResponse({"status": False, 'result': '淘宝登录过期'})
                        except Exception as e:
                            pass
                        try:
                            for a in data:
                                if not a:
                                    state = '%s 生意参谋数据正在更新，请稍后再试' % new_time
                                    i += 1
                                    break
                        # return JsonResponse({"status": False, 'result': '生意参谋数据正在更新，请稍后再试'})
                        except Exception as e:
                            pass

                        try:
                            obj.execute(
                                """select statDate from test_itemkeywords where statdate=%d and user=%d and store_name='%s' and goods_id=%d""" % (
                                    now_date_1, user_id, store_name, goods_id))
                            if not obj.fetchall():  # 防止存储重复数据
                                ItemKeywordsSQL(data, user_id, goods_id, store_name)  # 保存数据
                        except Exception as e:
                            return JsonResponse({"status": False, 'result': '保存数据失败'})
                        now_date_1 -= 86400
                        i += 1
                except Exception as e:
                    return JsonResponse({"status": False, 'result': '爬取服务器异常'})

            try:
                #     print('333333333333')
                query_data = instance_obj.select_data()
            except Exception as e:
                return JsonResponse({"status": False, 'result': '数据库查询失败'})

            # 组织数据
            day = (check - start) // 86400 + 1
            for i in query_data:
                priceValue = 0
                if i[10] and i[1]:
                    priceValue = (int(i[10]) / day) * (int(i[6]) / int(i[1]))

                data_dict = {}
                data_dict['keyword'] = i[0]  # 来源
                data_dict['uv'] = int(i[1])  # 访客数
                # data_dict['jpSelfUv'] = int(i[2])  # 店内跳转数
                # data_dict['jpUv'] = int(i[3])  # 店铺跳出数
                # data_dict['cltCnt'] = int(i[4])  # 收藏人数
                # data_dict['cartByrCnt'] = int(i[5])  # 加购数
                data_dict['payByrCnt'] = int(i[6])  # 支付买家数
                # data_dict['fansPayByrCnt'] = int(i[7])  # 粉丝支付买家数
                # data_dict['cltItmPayByrCnt'] = int(i[8])  # 收藏支付买家数
                # data_dict['ordItmPayByrCnt'] = int(i[9])  # 加购支付买家数
                data_dict['payRate'] = round(int(i[6]) / int(i[1]), 4) if i[1] and i[6] else 0  # 支付转化率
                data_dict['jpSelfUvRate'] = round(int(i[2]) / int(i[1]), 4) if i[1] and i[2] else 0  # 店内跳转率
                data_dict['jpUvRate'] = round(int(i[3]) / int(i[1]), 4) if i[1] and i[3] else 0  # 店铺跳出率
                data_dict['cltItmRate'] = round(int(i[4]) / int(i[1]), 4) if i[1] and i[4] else 0  # 收藏率
                data_dict['cartByrCntRate'] = round(int(i[5]) / int(i[1]), 4) if i[1] and i[5] else 0  # 加购率
                data_dict['fansRate'] = round(int(i[7]) / int(i[5]), 4) if i[5] and i[7] else 0  # 粉丝买家占比
                data_dict['cltItmConRate'] = round(int(i[8]) / int(i[4]), 4) if i[4] and i[8] else 0  # 收藏转化率
                data_dict['ordItmRate'] = round(int(i[9]) / int(i[5]), 4) if i[5] and i[9] else 0  # 加购转化率
                data_dict['priceValue'] = round(priceValue, 4)

                result.append(data_dict)

            instance_obj.the_end()  # 关闭数据库连接
            return JsonResponse({"status": True, 'result': result, 'state': state})
        else:
            return JsonResponse(is_Visit, status=200)


class ServiceIndicatorsView(View):
    """服务指标视图"""

    def post(self, request):
        # 获取参数
        user = request.POST.get('user')
        store_name = request.POST.get('store')
        start_str = request.POST.get('start')
        check_str = request.POST.get('check')
        cookie_str = request.POST.get('taobao')

        user = request.POST.get('user')
        is_Visit = permmsion_check(int(user), 3)

        if is_Visit['status'] == True:

            # 判断参数
            try:
                # 判断参数
                user_id = int(user)
                start = int(time.mktime(time.strptime(start_str, '%Y-%m-%d')))
                check = int(time.mktime(time.strptime(check_str, '%Y-%m-%d')))
                cookie = eval(cookie_str)
            except Exception as e:
                return JsonResponse({"status": False, 'result': '参数错误'})

            now_date = int(time.mktime(
                time.strptime(datetime.datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d'))) - 86400  # 前一天时间,时间戳
            con, obj = Link_database()  # 链接数据库
            result = []  # 最终数据结构
            state = ''  # 提示

            # 查询数据库最新数据
            obj.execute(
                """select statDate from serviceindicators where statdate=%d and user=%d and store_name='%s'""" % (
                    now_date, user_id, store_name))  # 查询前一天数据
            if not obj.fetchone():
                # if 1:
                obj.execute(
                    """select statDate from serviceindicators where user=%d and store_name='%s' order by statDate desc limit 1""" % (
                        user_id, store_name))  # 查询数据库中最新数据
                time_tuple = obj.fetchone()
                # 判断是否是新用户
                if not time_tuple:
                    crawler_check = time.strftime('%Y-%m-%d', time.localtime(now_date - 86400 * 29))  # 新用户时默认爬去三十天数据
                else:
                    storage_time = time_tuple[0]
                    difference = (now_date - storage_time) // 86400
                    # 判断缺省数据天数
                    if difference > 30:  # 爬虫最多爬取30天数据
                        crawler_check = time.strftime('%Y-%m-%d', time.localtime(now_date - 86400 * 29))
                    else:
                        crawler_check = time.strftime('%Y-%m-%d', time.localtime(storage_time + 86400))

                try:
                    # 调用爬虫，爬取数据
                    flow = Server_indicator_data()
                    now_date_str = time.strftime('%Y-%m-%d', time.localtime(now_date))
                    flow.dateRange = {"start_time": crawler_check, "end_time": now_date_str}
                    # flow.dateRange = {"start_time": '2018-10-24', "end_time": '2018-10-24'}
                    flow.cookies = cookie
                except Exception as e:
                    return JsonResponse({"status": False, 'result': '爬取服务器异常'})

                try:
                    data = flow.Any_day_data(flow.dateRange)  # 爬取数据
                # print(data)
                except Exception as e:
                    return JsonResponse({"status": False, 'result': '爬取数据失败'})

                # 判断爬虫cookie 是否失效
                try:
                    if data[0]['code'] == 5810:
                        return JsonResponse({"status": False, 'result': '淘宝登录过期'})
                    elif data[0]['code'] == 5924:
                        return JsonResponse({"status": False,
                                             'result': '亲，您暂时没有该模块的访问权限，需要由主账号或者有超级管理员权限的子账号到 子账号管理-员工管理 中修改岗位权限，开通 “生意参谋单店版服务洞察” 功能。'})
                    elif data[0]['code'] == 1003:
                        del data[0]
                        state = '%s 生意参谋数据正在更新，请稍后再试' % now_date_str
                # return JsonResponse({"status": False, 'result': '生意参谋数据正在更新，请稍后再试'})
                except Exception as e:
                    pass

                try:
                    # print(data)
                    obj.execute(
                        """select statDate from serviceindicators where statdate=%d and user=%d and store_name='%s'""" % (
                            now_date, user_id, store_name))
                    if not obj.fetchall():
                        # 保存数据
                        ServiceIndicatorsSQL(data, user_id, store_name)
                except Exception as e:
                    return JsonResponse({"status": False, 'result': '数据保存失败'})

            try:
                # 查询数据库
                query_data = ServiceIndicators(user_id, store_name, start, check)
            except Exception as e:
                return JsonResponse({"status": False, 'result': '数据查询失败'})

            try:
                # 组织返回数据
                for i in query_data:
                    re = {"data": {
                        # "statDate": {"value": time.strftime('%Y-%m-%d', time.localtime(i[0]))},
                        "statDate": {"value": i[0] * 1000},
                        "rfdSucRate": {"value": i[1]},
                        "rfdEndRate": {"value": i[2]},
                        "rfdDsptRate": {"value": i[3]},
                        "csInRfdRate": {"value": i[4]},
                        "cmptRate": {"value": i[5]},
                        "rfdAvgEndTime": {"value": i[6]},
                        "rfdGoodsAvgEndTime": {"value": i[7]},
                        "svrRankExceedRate": {"value": i[8]}
                    }
                    }
                    result.append(re)
            except Exception as e:
                return JsonResponse({"status": False, 'result': '数据组织失败'})

            # 判断数据完整性,返回数据
            date = (check - start) // 86400

            if date + 1 == len(query_data):
                return JsonResponse({'status': True, 'result': result, 'state': state}, status=200)
            else:
                return JsonResponse({'status': True, 'result': result, 'state': state}, status=200)
        else:
            return JsonResponse(is_Visit, status=200)


class BindingGoodsView(View):
    """单品分析 绑定商品显示视图"""

    def post(self, request):
        # 获取参数
        user_str = request.POST.get('user')
        store_main = request.POST.get('store')
        user = request.POST.get('user')
        is_Visit = permmsion_check(int(user), 3)

        if is_Visit['status'] == True:

            # 判断参数
            try:
                user_id = int(user_str)
            except Exception as e:
                return JsonResponse({'status': True, 'result': '参数错误'})

            con, obj = Link_database()  # 链接数据库
            result = []  # 返回数据

            try:
                sql_1 = """select goods_id from item_associated where user_id=%d and store_name='%s'""" % (
                    user_id, store_main)
                obj.execute(sql_1)
                associated_goods_id = obj.fetchall()
            except Exception as e:
                return JsonResponse({'status': False, 'result': '查询关联表失败'})
            if not associated_goods_id:
                return JsonResponse({'status': True, 'result': result})

            select_list = [0]
            for i in associated_goods_id:
                for a in i:
                    select_list.append(a)

            select_tuple = tuple(select_list)
            try:
                sql_2 = """select goods_id,title from itemanalysis where user={} and store_name='{}' and goods_id in {} group by goods_id""".format(
                    user_id, store_main, select_tuple)
                obj.execute(sql_2)
                goods_information = obj.fetchall()
            except Exception as e:
                return JsonResponse({'status': False, 'result': '查询商品id，名失败'})

            try:
                goods_id_list = []
                for data in goods_information:
                    goods_id_list.append(data[0])
                    data_dict = {}
                    data_dict['goods_id'] = data[0]
                    data_dict['title'] = data[1]
                    result.append(data_dict)
            except Exception as e:
                return JsonResponse({'status': True, 'result': '数据组织失败'})
            try:
                for n in select_tuple[1:]:
                    if n not in goods_id_list:
                        sql = """delete from item_associated where user_id=%d and store_name='%s' and goods_id=%d""" % (
                        user_id, store_main, n)
                        obj.execute(sql)
                        con.commit()
            except Exception as e:
                return JsonResponse({'status': False, 'result': '删除关联表失败', 'e': str(e)})

            # 关闭数据库连接
            obj.close()
            con.close()

            return JsonResponse({'status': True, 'result': result})
        else:
            return JsonResponse(is_Visit, status=200)


# class BDKeyGoodsVi(View):
# 	"""单品关键词 绑定商品显示视图"""
# 	def post(self, request):
# 		# 获取参数
# 		user_str = request.POST.get('user')
# 		store_name = request.POST.get('store')
# 		user = request.POST.get('user')
# 		is_Visit = permmsion_check(int(user), 3)

# 		if is_Visit['status'] == True:
# 			try:
# 				# 判断参数
# 				user_id = int(user_str)
# 			except Exception as e:
# 				return JsonResponse({'status': True, 'result': '参数错误'})

# 			con, obj = Link_database()  # 链接数据库
# 			result = []  # 返回数据

# 			try:
# 				# 查询关系表
# 				sql_1 = """select goods_id from keywords_associated where user_id=%d and store_name='%s'""" % (user_id, store_name)
# 				obj.execute(sql_1)
# 				associated_goods_id = obj.fetchall()
# 				# print(associated_goods_id)
# 			except Exception as e:
# 				return JsonResponse({'status': True, 'result': '查询关联表失败'})

# 			if not associated_goods_id:
# 				return JsonResponse({'status': True, 'result': result})

# 			# select_list = [0]
# 			# for i in associated_goods_id:
# 			#     for a in i:
# 			#         select_list.append(a)
# 			#
# 			# select_tuple = tuple(select_list)
# 			# try:
# 			#     sql_2 = """select goods_id from itemkeywords where user={} and store_name='{}' and goods_id in {} group by goods_id""".format(user_id, store_name, select_tuple)
# 			#     obj.execute(sql_2)
# 			#     goods_information = obj.fetchall()
# 			#     # print(goods_information)
# 			# except Exception as e:
# 			#     return JsonResponse({'status': True, 'result': '查询商品id，名失败'})

# 			# 关闭数据库连接
# 			obj.close()
# 			con.close()

# 			try:
# 				for data in associated_goods_id:
# 					data_dict = {}
# 					data_dict['goods_id'] = data[0]
# 					# data_dict['title'] = data[1]
# 					result.append(data_dict)
# 			except Exception as e:
# 				return JsonResponse({'status': True, 'result': '数据组织失败'})

# 			return JsonResponse({'status': True, 'result': result})
# 		else:
# 			return JsonResponse(is_Visit, status=200)


class KeywordsView(View):
    """关键词具体数据视图"""

    def post(self, request):
        # 获取参数
        user_str = request.POST.get('user')
        store_name = request.POST.get('store')
        goods_str = request.POST.get('goods')
        keywords = request.POST.get('keywords')
        start_str = request.POST.get('start')
        check_str = request.POST.get('check')

        user = request.POST.get('user')
        is_Visit = permmsion_check(int(user), 3)

        if is_Visit['status'] == True:

            try:
                # 判断参数
                user_id = int(user_str)
                goods_id = int(goods_str)
                start = int(time.mktime(time.strptime(start_str, '%Y-%m-%d')))
                check = int(time.mktime(time.strptime(check_str, '%Y-%m-%d')))
            except Exception as e:
                return JsonResponse({"status": False, 'result': '参数错误'})

            try:
                # 查询数据
                query_data = SelectKey(user_id, store_name, goods_id, keywords, start, check)
            # print(query_data)
            except Exception as e:
                return JsonResponse({"status": False, 'result': '查询数据失败'})

            result = []
            if not query_data:
                return JsonResponse({"status": True, 'result': result})

            try:
                # 组织数据
                for i in query_data:
                    fansRate = 0
                    cltItmConRate = 0
                    ordItmRate = 0
                    priceValue = 0
                    if i[5]:
                        fansRate = round(int(i[7]) / int(i[5]), 4) if int(i[5]) and i[7] else 0
                        ordItmRate = round(int(i[9]) / int(i[5]), 4) if int(i[5]) and i[9] else 0
                    if i[4]:
                        cltItmConRate = round(int(i[8]) / int(i[4]), 4) if int(i[4]) and i[8] else 0
                    if i[6] and i[1] and i[10]:
                        priceValue = round((int(i[6]) / int(i[1])) * float(i[10]), 4) if int(i[6]) and int(
                            i[1]) and float(i[10]) else 0
                    data_dict = {}
                    data_dict['statDate'] = i[0]  # 时间
                    data_dict['uv'] = int(i[1])  # 访客数
                    data_dict['payByrCnt'] = int(i[6]) if i[6] else 0  # 支付买家数
                    data_dict['payRate'] = round(int(i[6]) / int(i[1]), 4) if i[1] and i[6] else 0  # 支付转化率
                    data_dict['jpSelfUvRate'] = round(int(i[2]) / int(i[1]), 4) if i[1] and i[2] else 0  # 店内跳转率
                    data_dict['jpUvRate'] = round(int(i[3]) / int(i[1]), 4) if i[1] and i[3] else 0  # 店铺跳出率
                    data_dict['cltItmRate'] = round(int(i[4]) / int(i[1]), 4) if i[1] and i[4] else 0  # 收藏率
                    data_dict['cartByrCntRate'] = round(int(i[5]) / int(i[1]), 4) if i[1] and i[5] else 0  # 加购率
                    data_dict['fansRate'] = fansRate  # 粉丝买家占比
                    data_dict['cltItmConRate'] = cltItmConRate  # 收藏转化率
                    data_dict['ordItmRate'] = ordItmRate  # 加购转化率
                    data_dict['priceValue'] = priceValue  # Uv价值

                    result.append(data_dict)

                date_list = []
                for a in query_data:
                    date_list.append(int(a[0]))

                c = 0
                number = (check - start) // 86400 + 1
                # print(number)
                # print(date_list)
                while c < number:
                    statdate = start + c * 86400
                    # print(statdate)
                    if statdate not in date_list:
                        datas = {}
                        datas['statDate'] = statdate
                        datas['uv'] = 0
                        datas['payByrCnt'] = 0
                        datas['payRate'] = 0
                        datas['jpSelfUvRate'] = 0
                        datas['jpUvRate'] = 0
                        datas['cltItmRate'] = 0
                        datas['cartByrCntRate'] = 0
                        datas['fansRate'] = 0
                        datas['cltItmConRate'] = 0
                        datas['ordItmRate'] = 0
                        datas['priceValue'] = 0

                        result.append(datas)
                    c += 1

            except Exception as e:
                return JsonResponse({"status": False, 'result': '数据组织失败', 'e': e})
            # print(len(result))
            # date = (check - start) // 86400 + 1
            # if date == len(result):
            #     return JsonResponse({"status": True, 'result': result})
            # else:
            #     return JsonResponse({"status": True, 'result': result})
            return JsonResponse({"status": True, 'result': result})
        else:
            return JsonResponse(is_Visit, status=200)


class ItemAnalysisView(View):
    """单品数据分析视图"""

    def post(self, request):
        # 获取参数
        user = request.POST.get('user')
        store_name = request.POST.get('store')
        start_str = request.POST.get('start')
        check_str = request.POST.get('check')
        cookie_str = request.POST.get('taobao')
        goods_str = request.POST.get('goods')

        user = request.POST.get('user')
        is_Visit = permmsion_check(int(user), 3)

        if is_Visit['status'] == True:

            # 判断参数
            try:
                # 判断参数
                user_id = int(user)
                goods_id = int(goods_str)
                start = int(time.mktime(time.strptime(start_str, '%Y-%m-%d')))
                check = int(time.mktime(time.strptime(check_str, '%Y-%m-%d')))
                cookie = eval(cookie_str)
            except Exception as e:
                return JsonResponse({"status": False, 'result': '参数错误'})

            now_date = int(time.mktime(
                time.strptime(datetime.datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d'))) - 86400  # 前一天时间,时间戳
            con, obj = Link_database()  # 链接数据库
            state = ''  # 提示
            total_list = []  # 返回数据

            try:
                instance_obj = ItemAnalysis(user_id, store_name, start, check, goods_id)  # 实例查询类
                vip_sql = """select vip_level from auth_user where id=%d""" % user_id
                obj.execute(vip_sql)
                vip_level = int(obj.fetchone()[0])  # vip等级
            except Exception as e:
                return JsonResponse({"status": False, 'result': '查询用户失败'})

            try:
                # 查询关系表
                bools = instance_obj.select_goods_id()  # 查询商品
                if not bools:
                    num_tuple = instance_obj.select_associatcd_num()  # 查询商品id 数量
                    if num_tuple:
                        if vip_level <= 3:
                            if num_tuple[1] >= 3:
                                return JsonResponse({"status": False, 'result': '亲，你的账号只能绑定三个商品'})
                            else:
                                instance_obj.save_associatcd_table()  # 绑定数量小于三个 保存
                        elif vip_level > 3 and vip_level <= 5:
                            if num_tuple[1] >= 6:
                                return JsonResponse({"status": False, 'result': '亲，你的账号只能绑定六个商品'})
                            else:
                                instance_obj.save_associatcd_table()  # 绑定数量小于六个 保存
                    else:
                        instance_obj.save_associatcd_table()  # 用户未绑定过 保存

            # query_goods_id = instance_obj.select_associatcd_table()  # 保存后再查询
            except Exception as e:
                return JsonResponse({"status": False, 'result': '关联表失败'})

            # goods_id_list = []
            # for query in query_goods_id:
            #     goods_id_list.append(query[0])

            # select_goods_id = goods_id_list
            # select_goods_id.append(0)
            # goods_id_set = tuple(select_goods_id)  # 查询时用到的商品 id 数据格式
            # for c in goods_id_list:

            # 查询数据库最新数据
            obj.execute(
                """select statDate from itemanalysis where statdate=%d and user=%d and store_name='%s' and goods_id=%d""" % (
                    now_date, user_id, store_name, goods_id))  # 查询前一天数据
            if not obj.fetchone():
                # if 1:
                obj.execute(
                    """select statDate from itemanalysis where user=%d and store_name='%s' and goods_id=%d order by statDate desc limit 1""" % (
                        user_id, store_name, goods_id))  # 查询数据库中最新数据
                time_tuple = obj.fetchone()
                # 判断是否是新用户
                if not time_tuple:
                    crawler_check = time.strftime('%Y-%m-%d', time.localtime(now_date - 86400 * 29))  # 新用户时默认爬去三十天数据
                else:
                    storage_time = time_tuple[0]
                    difference = (now_date - storage_time) // 86400
                    # 判断缺省数据天数
                    if difference > 30:  # 爬虫最多爬取30天数据
                        crawler_check = time.strftime('%Y-%m-%d', time.localtime(now_date - 86400 * 29))
                    else:
                        crawler_check = time.strftime('%Y-%m-%d', time.localtime(storage_time + 86400))

                try:
                    # 调用爬虫，爬取数据
                    flow = prodouct_data_analysis()
                    now_date_str = time.strftime('%Y-%m-%d', time.localtime(now_date))
                    # print(crawler_check)
                    # print(now_date_str)
                    flow.dateRange = {"start_time": crawler_check, "end_time": now_date_str}
                    # flow.dateRange = {"start_time": '2018-10-26', "end_time": '2018-10-26'}
                    flow.cookies = cookie
                except Exception as e:
                    return JsonResponse({"status": False, 'result': '爬取服务器异常'})

                try:
                    data = flow.Serch_Goods([goods_id])
                # print(data)
                except Exception as e:
                    return JsonResponse({"status": False, 'result': '爬取数据失败'})

                # 判断爬虫cookie 是否失效
                try:
                    for i in data:
                        if not i['data']['data']:
                            pass
                        # instance_obj.delete_goods_id(c)
                        # return JsonResponse({"status": False, 'result': '%d:商品id错误，或生意参谋数据正在更新，请稍后再试' % goods_id})
                except Exception as e:
                    pass
                try:
                    if data[0]['code'] == 5810:
                        return JsonResponse({"status": False, 'result': '淘宝登录过期'})
                except Exception as e:
                    pass

                # try:
                obj.execute(
                    """select statDate from itemanalysis where statdate=%d and user=%d and store_name='%s' and goods_id=%d""" % (
                        now_date, user_id, store_name, goods_id))  # 查询前一天数据
                if not obj.fetchone():
                    # 保存数据
                    # print(data)
                    ItemAnalysisSQL(data, user_id, store_name)
                    n = instance_obj.select_data(goods_id)
                    # print(n)
                    time.sleep(10)
            # except Exception as e:
            #     return JsonResponse({"status": False, 'result': '数据保存失败','e':e})

            try:
                # 查询数据库
                map_query_daya = instance_obj.select_data(goods_id)  # 查询每天数据
            # print(map_query_daya)
            # sum_query_daya = instance_obj.select_sum_data(goods_id_set)  # 查询数据总和
            except Exception as e:
                return JsonResponse({"status": False, 'result': '数据查询失败'})

            try:
                # 组织返回数据
                day_list = []
                for a in map_query_daya:
                    if a[7] and a[6] and a[13]:
                        refund_rate = float(a[13]) / (float(a[6]) / a[7]) / a[7]
                    else:
                        refund_rate = 0
                    article = {
                        "itemId": a[1],  # id
                        "statDate": time.strftime('%Y-%m-%d', time.localtime(a[0])),  # 时间
                        "itemEffectIndex": {
                            # "id": a[1],
                            "itemUv": a[2],  # 访客数
                            "payRate": a[3],  # 支付转化率
                            "average_time": round(float(a[4]), 2) if a[4] else 0,  # 平均时长
                            "out_rate": round(float(a[5]), 4) if a[5] else 0,  # 详情跳出率
                            "payAmt": round(float(a[6]), 2) if a[6] else 0,  # 支付金额
                            "pay_buyers": a[7],  # 支付买家数
                            # "pay_old_buyers": a[8],  # 支付老买家数
                            # "pay_a_number": a[9],  # 支付件数
                            "uvAvgPayAmt": a[11],  # 访问平均价值
                            # "favBuyerCnt": a[12],  # 收藏人数
                            "payPct": round(float(a[6]) / a[7], 2) if a[7] and a[6] else 0,  # 客单价
                            # "refund_amount": a[13],  # 退款金额
                            "month_pay_a_number": a[14],  # 月支付件数
                            "collection_rate": round(a[12] / a[2], 4) if a[2] else 0,  # 收藏率
                            "purchased_rate": round(a[10] / a[2], 4) if a[2] else 0,  # 加购率
                            "people_avg_number": round(a[9] / a[7], 4) if a[7] else 0,  # 人均支付件数
                            "pay_old_buyers_rate": round(a[8] / a[7], 4) if a[7] else 0,  # 老买家占比
                            "refund_rate": round(refund_rate, 4)  # 退款率
                            # "sePayRate": a[9],  #
                            # "uvSe": a[10]
                        },
                        # "addCartBuyerCnt": a[10],  # 加购人数
                        "itemModel": {"title": a[15]},  # 商品名
                    }
                    day_list.append(article)
                total_list.append(day_list)

            except Exception as e:
                return JsonResponse({"status": False, 'result': '数据组织失败', 'e': str(e)})

            result = {"map": total_list}
            # result = []
            instance_obj.the_end()  # 关闭数据库连接，游标
            # 判断数据完整性,返回数据
            # date = (check - start) // 86400 + 1
            # try:
            #     if date == len(total_list[0]):  # 一个商品id 一天一条数据
            #         return JsonResponse({'status': True, 'result': result, 'state': state}, status=200)
            #     else:
            #         return JsonResponse({'status': True, 'result': result, 'state': state}, status=200)
            # except Exception as e:
            #     return JsonResponse({'status': True, 'result': result, 'state': state}, status=200)
            return JsonResponse({'status': True, 'result': result, 'state': state}, status=200)
        else:
            return JsonResponse(is_Visit, status=200)


class DeleteItemDataView(View):
    """删除单品数据视图"""

    def post(self, request):
        # 获取参数
        user_str = request.POST.get('user')
        goods_str = request.POST.get('goods')
        store_name = request.POST.get('store')

        try:
            # 判断参数
            user_id = int(user_str)
            goods_id = int(goods_str)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '参数错误'})

        try:
            # 删除
            del_obj = del_data(user_id, goods_id, store_name)
            del_obj.del_ItemAnalysis()
            del_obj.del_ItemKeywords()
            del_obj.del_BindingGoods()
            del_obj.del_commit()
            del_obj.the_end()
        except Exception as e:
            return JsonResponse({"status": False, 'result': '删除数据失败'})

        return JsonResponse({"status": True, 'result': '数据已删除'})


class CategoryComposition(View):
    """类目构成视图"""

    def post(self, request):
        user = request.POST.get('user')
        statdate = request.POST.get('time')
        taobao = request.POST.get('taobao')

        is_Visit = permmsion_check(int(user), 3)

        if is_Visit['status'] == True:

            try:
                statdate = statdate[10:17]
                user_id = int(user)
                cookie = json.loads(taobao)
            except Exception as e:
                return JsonResponse({"status": False, 'result': '参数错误'})

            con, obj = Link_database()  # 链接数据库

            month = datetime.datetime.now().strftime('%Y-%m')  # 当前月份
            category_composition = Category_composition()  # 爬虫实例
            category_composition.cookies = cookie

            on_list = month.split('-')
            y_1 = int(on_list[0])  # y_1 : 上月年份   y_2: 数据库最新数据年份  y: 爬虫年份
            m_1 = int(on_list[1]) - 1  # m_1 ：上月月份   m_2：数据库最新数据月份   m: 爬虫月份
            if m_1 < 1:
                y_1 = int(on_list[0]) - 1
                m_1 = 12 + m_1
            on_month = '-'.join([str(y_1), str(m_1)])
            on_statdate = int(time.mktime(time.strptime(on_month, '%Y-%m')))  # 上月时间

            sql_1 = """select statdate from category_structure where user_id=%d and statdate=%d""" % (
                user_id, on_statdate)
            obj.execute(sql_1)

            if not obj.fetchone():
                sql_2 = """select statdate from category_structure where user_id=%d order by statdate desc limit 1""" % user_id
                obj.execute(sql_2)
                query_1 = obj.fetchone()
                if not query_1:
                    num = 13
                else:
                    query_date = time.strftime('%Y-%m', time.localtime(query_1[0]))  # 数据库中最新数据时间月份
                    y_2 = int(query_date.split('-')[0])
                    m_2 = int(query_date.split('-')[1])
                    num = (m_1 - m_2) + 1
                    if (y_1 - y_2) == 1:
                        num += 12

                if num > 13:
                    num = 13
                # print(num)
                i = 1
                while i < num:
                    time.sleep(0.5)
                    # 计算月份
                    date_list = month.split('-')
                    y = date_list[0]
                    m = int(date_list[1]) - i
                    if m < 1:
                        y = int(date_list[0]) - 1
                        m = 12 + m
                    date = '-'.join([str(y), str(m)])
                    time_data = dateAnay(date)  # 月份天数函数  '2018-7-1|2018-7-30'
                    # print(time_data)
                    category_composition.dateRange = time_data
                    try:
                        fat = category_composition.Category()
                        try:
                            if fat['code'] == 5810:
                                return JsonResponse({"status": False, 'result': '淘宝登录过期'})
                        except Exception as e:
                            pass

                        # 处理子类数据
                        cateIList = []
                        for a in fat['data']['levelOneCategoryBOList']:
                            time.sleep(3)
                            for h in (category_composition.Category_son(a['cateId'])):
                                h['fname'] = a['cateName']
                                cateIList.append(h)
                    except Exception as e:
                        del_category(user_id, on_month, date)  # 爬虫异常时删除此次数据库中爬取的所有数据
                        return JsonResponse({"status": False, 'result': '网络不稳定请再次尝试'})

                    try:
                        # print(cateIList)
                        Category_SQL(cateIList, date, user_id)
                    except Exception as e:
                        return JsonResponse({"status": False, 'result': '保存数据失败'})
                    i += 1

            try:
                # 查询
                query_data = When_Month(user_id, statdate)
            except Exception as e:
                return JsonResponse({"status": False, 'result': '查询数据失败'})

            if not query_data:
                return JsonResponse({"status": True, 'result': []})

            result = []
            try:
                for i in query_data:
                    data_dict = {}
                    data_dict['statDate'] = i[0]
                    data_dict['fname'] = i[1]
                    data_dict['cateName'] = i[2]
                    data_dict['payAmt'] = i[3]
                    data_dict['payAmtRate'] = i[4]
                    data_dict['payBuyerCnt'] = i[5]
                    data_dict['payrate'] = i[6]

                    result.append(data_dict)
            except Exception as e:
                return JsonResponse({"status": False, 'result': '数据整理失败'})

            return JsonResponse({"status": True, 'result': result})
        else:
            return JsonResponse(is_Visit, status=200)


class CategoryDetails(View):
    """类目详情视图"""

    def post(self, request):
        user = request.POST.get('user')
        fname = request.POST.get('fname')
        catename = request.POST.get('catename')
        statdate = request.POST.get('time')

        is_Visit = permmsion_check(int(user), 3)

        if is_Visit['status'] == True:

            try:
                statdate = statdate[10:17]
                user_id = int(user)
            except Exception as e:
                return JsonResponse({"status": False, 'result': '参数错误'})

            y, m = statdate.split('-')  # y: 查询时间年份  y_1: 前十二月年份时间  y_2: 十二个月中每个月年时间
            m_1 = int(m) + 12 - 11  # m: 查询时间月份  m_1: 前十二月月份时间  m_2; 十二个月每月个月月时间
            if m_1 > 12:
                y_1 = y
                m_1 = 1
            else:
                y_1 = str(int(y) - 1)
            start_str = '-'.join([y_1, str(m_1)])  # 起始时间
            # print(start_str)
            # 每月时间戳
            time_month = []  # 十二个月每月时间戳 列表
            i = 0
            while i < 12:
                date_list = statdate.split('-')
                y_2 = date_list[0]
                m_2 = int(date_list[1]) - i
                if m_2 < 1:
                    y_2 = int(date_list[0]) - 1
                    m_2 = 12 + m_2
                date = '-'.join([str(y_2), str(m_2)])
                # print(date)
                time_month.append(int(time.mktime(time.strptime(date, '%Y-%m'))))
                i += 1

            try:
                # 数据库查询
                start = int(time.mktime(time.strptime(start_str, '%Y-%m')))
                check = int(time.mktime(time.strptime(statdate, '%Y-%m')))
                # print(start)
                # print(check)
                query_data = Before_Month(user_id, fname, catename, start, check)
            except Exception as e:
                return JsonResponse({"status": False, 'result': '数据查询失败'})

            result = []  # 返回数据机构

            if not query_data:
                return JsonResponse({"status": True, 'result': result})

            time_list = []  # 已有数据时间列表
            try:
                # 组织数据
                for i in query_data:
                    data_dict = {}
                    data_dict['statDate'] = i[0]
                    data_dict['fname'] = i[1]
                    data_dict['cateName'] = i[2]
                    data_dict['payAmt'] = i[3]
                    data_dict['payAmtRate'] = i[4]
                    data_dict['payBuyerCnt'] = i[5]
                    data_dict['payrate'] = i[6]

                    result.append(data_dict)
                    time_list.append(i[0])

                for a in time_month:
                    if a not in time_list:
                        empty = {}
                        empty['statDate'] = a
                        empty['fname'] = fname
                        empty['cateName'] = catename
                        empty['payAmt'] = 0
                        empty['payAmtRate'] = 0
                        empty['payBuyerCnt'] = 0
                        empty['payrate'] = 0

                        result.append(empty)

            except Exception as e:
                return JsonResponse({"status": False, 'result': '数据组织失败'})

            return JsonResponse({"status": True, 'result': result})

        else:
            return JsonResponse(is_Visit, status=200)


class PublishedView(View):
    """发表文章视图"""

    def post(self, request):
        # 获取参数
        title = request.POST.get('title')  # 标题
        article_simple = request.POST.get('description')  # 内容简介
        cover_photo = request.POST.get('image')  # 封面图片
        published_name = request.POST.get('author')  # 发表人
        content = request.POST.get('content')  # 内容

        # if not title:
        #     return JsonResponse({"status": False, 'result': '标题'})
        # if not article_simple:
        #     return JsonResponse({"status": False, 'result': '内容简介'})
        # if not cover_photo:
        #     return JsonResponse({"status": False, 'result': '封面图片'})
        # if not published_name:
        #     return JsonResponse({"status": False, 'result': '发表人'})
        # if not content:
        #     return JsonResponse({"status": False, 'result': '内容'})

        if not all([title, article_simple, cover_photo, published_name, content]):
            return JsonResponse({"status": False, 'result': '缺少参数'})

        try:
            # 处理数据
            url = ''
            img_b64_list = re.findall(r'<img src="data:image/(?:jpeg|png|jpg|gif);base64,(.*?)">', content)
            # print(len(img_b64_list))
            cover_photo = re.findall(r'data:image/(?:jpeg|png|jpg|gif);base64,(.*)', cover_photo)[0]
        except Exception as e:
            return JsonResponse({"status": False, 'result': '封面数据问题'})
        # print(cover_photo)
        # print('1111111111')
        # print(img_b64_list)
        # print(len(img_b64_list))
        try:
            img_b64_list.append(cover_photo)
            for i in img_b64_list:
                c = base64.b64decode(i)
                with open('1.png', 'wb') as f:
                    f.write(c)
                    f.close()

                # 将图片上传七牛云
                with open('1.png', 'rb') as f:
                    b = f.read()
                    qiniu_address = storage(b)
                    if qiniu_address == '上传七牛失败':
                        return JsonResponse({"status": False, 'result': '上传图片失败'})
                    url = 'http://pbh0zc0bs.bkt.clouddn.com/' + qiniu_address

                    # 将内容中的图片替换成 url地址
                    content = re.sub(r'<img src="data:image/(?:jpeg|png|jpg|gif);base64,.*?">',
                                     '<img src="' + url + '">', content, count=1)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '文件处理失败'})

        try:
            # 数据保存
            DryCargoSQL(title, article_simple, url, content, published_name)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '数据存储失败'})

        return JsonResponse({"status": True, 'result': '保存成功'})


class QueryAllView(View):
    """查询所有文字视图"""

    def get(self, request):
        # try:
        #     # 查询
        query_obj = QueryBBS()
        query_data = query_obj.QueryAllBBS()
        query_obj.the_end()
        # except Exception as e:
        #     return JsonResponse({"status": False, 'result': str(e)})

        if not query_data:
            return JsonResponse({"status": True, 'result': '论坛暂无数据，快去填写把'})

        try:
            data = []  # 最终数据结构
            # 组织数据
            for i in query_data:
                query_dict = {}
                query_dict['title'] = i[0]
                query_dict['description'] = i[1]
                query_dict['image'] = i[2]
                query_dict['praise_number'] = i[3]
                query_dict['statdate'] = i[4]
                query_dict['author'] = i[5]
                query_dict['id'] = i[6]

                data.append(query_dict)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '数据组织失败'})

        return JsonResponse({"status": True, 'result': data})


class DetailsBBSView(View):
    """文章详情试图"""

    def get(self, request):
        # 获取参数
        id = request.GET.get('id')

        try:
            id = int(id)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '参数错误'})

        try:
            # 查询
            query_obj = QueryBBS()
            query_data = query_obj.DetailsBBS(id)
            query_obj.the_end()
        except Exception as e:
            return JsonResponse({"status": False, 'result': '数据查询失败'})

        if not query_data:
            return JsonResponse({"status": False, 'result': '次id：%d 无数据' % id})

        try:
            # content = re.sub(r'', '', query_data[1])

            data = {}
            data['title'] = query_data[0]
            data['content'] = query_data[1]
            data['statdate'] = query_data[2]
            data['author'] = query_data[3]
            data['description'] = query_data[4]
        except Exception as e:
            return JsonResponse({"status": False, 'result': '数据组织失败'})

        return JsonResponse({"status": True, 'result': data})


class DeleteBBSView(View):
    """删除文章视图"""

    def post(self, request):
        # 获取参数
        id = request.POST.get('id')

        try:
            id = int(id)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '参数错误'})

        con, obj = Link_database()

        sql = """delete from dry_cargo_bbs where id=%d""" % id
        obj.execute(sql)
        con.commit()

        obj.close()
        con.close()

        return JsonResponse({"status": True, 'result': '删除成功'})


class ChangeBBSView(View):
    """修改文章视图"""

    def get(self, request):
        """查找修改文章"""
        # 接受参数
        id = request.GET.get('id')

        if not id:
            return JsonResponse({"status": False, 'result': '缺省参数'})
        try:
            id = int(id)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '参数错误'})

        try:
            # 查询
            query_obj = QueryBBS()
            query_data = query_obj.UpdateSelect(id)
            query_obj.the_end()
        except Exception as e:
            return JsonResponse({"status": False, 'result': '数据查询失败'})

        if not query_data:
            return JsonResponse({"status": False, 'result': '无此id文章'})

        try:
            # 数据整理
            data = {}
            data['title'] = query_data[0]
            data['description'] = query_data[1]
            data['image'] = query_data[2]
            data['author'] = query_data[4]
            data['content'] = query_data[3]
            data['id'] = query_data[5]
        except Exception as e:
            return JsonResponse({"status": False, 'result': '数据整理失败'})

        return JsonResponse({"status": True, 'result': data})

    def post(self, request):
        """x修改文章"""
        # 接受参数
        id = request.POST.get('id')
        title = request.POST.get('title')  # 标题
        article_simple = request.POST.get('description')  # 内容简介
        cover_photo = request.POST.get('image')  # 封面图片
        published_name = request.POST.get('author')  # 发表人
        content = request.POST.get('content')  # 内容
        # print(content)

        if not all([id, title, article_simple, cover_photo, published_name, content]):
            return JsonResponse({"status": False, 'result': '缺少参数'})

        try:
            id = int(id)
        except Exception as e:
            return JsonResponse({"status": False, 'result': 'id请传整数'})

        try:
            # 处理数据
            url = ''
            img_b64_list = re.findall(r'<img src="data:image/(?:jpeg|png|jpg|gif);base64,(.*?)">', content)
            cover_photo_list = re.findall(r'data:image/(?:jpeg|png|jpg|gif);base64,(.*)', cover_photo)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '封面数据问题'})

        if cover_photo_list:
            cover_photo = cover_photo_list[0]
            if not cover_photo[-1] == '=':
                cover_photo += '='
            img_b64_list.append(cover_photo)
        # print(img_b64_list)
        try:
            for i in img_b64_list:

                c = base64.b64decode(i)
                with open('1.png', 'wb') as f:
                    f.write(c)
                    f.close()

                # 将图片上传七牛云
                with open('1.png', 'rb') as f:
                    b = f.read()
                    qiniu_address = storage(b)
                    if qiniu_address == '上传七牛失败':
                        return JsonResponse({"status": False, 'result': '上传图片失败'})
                    url = 'http://pbh0zc0bs.bkt.clouddn.com/' + qiniu_address

                    # 将内容中的图片替换成 url地址
                    content = re.sub(r'<img src="data:image/(?:jpeg|png|jpg|gif);base64,.*?">',
                                     '<img src="' + url + '">', content,
                                     count=1)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '文件处理失败'})

        try:
            # 修改文章
            UpdateDrySQL(title, article_simple, url, content, published_name, id)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '修改文章失败'})

        return JsonResponse({"status": True, 'result': '修改文章成功'})


class GiveLikeView(View):
    """点赞视图"""

    def get(self, request):
        id = request.GET.get('id')

        if not id:
            return JsonResponse({"status": False, 'result': '缺省参数'})
        try:
            id = int(id)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '参数错误'})

        try:
            # 查询
            query_obj = QueryBBS()
            query_data = query_obj.GiveLike(id)
            query_obj.the_end()
        except Exception as e:
            return JsonResponse({"status": False, 'result': '数据查询失败'})

        if not query_data:
            return JsonResponse({"status": False, 'result': '数据库无此id'})

        num = int(query_data[0]) + 1
        # print(num)
        try:
            LikeSQL(num, id)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '数据库操作失败'})

        return JsonResponse({"status": True, 'result': '点赞成功'})


class UserData(View):
    """后台所有用户资料"""

    def get(self, request):
        pages = request.GET.get('page')
        # if not pages:
        #     try:
        #         # 查询
        #         obj = Admin_after()
        #         query_data = obj.all_data()
        #     except Exception as e:
        #         return JsonResponse({"status": False, 'result': '查询数据库失败', 'e': str(e)})
        # else:
        try:
            page = (int(pages) - 1) * 25
        except Exception as e:
            return JsonResponse({"status": False, 'result': '参数错误'})
        try:
            # 查询
            obj = Admin_after()
            number = obj.all_data()
            query_data = obj.all_page_data(page)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '查询数据库失败', 'e': str(e)})

        try:
            # 组织数据
            result = after_data(query_data)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '组织数据失败', 'e': str(e)})

        return JsonResponse({"status": True, 'result': result, "number": number})


class NotPayment(View):
    """后台未付款用户资料"""

    def get(self, request):
        try:
            # 查询
            obj = Admin_after()
            query_data = obj.not_payment()
        except Exception as e:
            return JsonResponse({"status": False, 'result': '查询数据库失败', 'e': e})

        try:
            # 组织数据
            result = after_data(query_data)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '组织数据失败'})

        return JsonResponse({"status": True, 'result': result})


class WillDueTo(View):
    """vip将到期用户资料"""

    def get(self, request):
        try:
            # 查询
            obj = Admin_after()
            query_data = obj.will_due_to()
        except Exception as e:
            return JsonResponse({"status": False, 'result': '查询数据库失败', 'e': e})

        try:
            # 组织数据
            result = after_data(query_data)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '组织数据失败'})

        return JsonResponse({"status": True, 'result': result})


class DueTo(View):
    """vip到期用户资料"""

    def get(self, request):
        try:
            # 查询
            obj = Admin_after()
            query_data = obj.due_to()
        except Exception as e:
            return JsonResponse({"status": False, 'result': '查询数据库失败', 'e': e})

        try:
            # 组织数据
            result = after_data(query_data)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '组织数据失败'})

        return JsonResponse({"status": True, 'result': result, "datalen": len(result)})


# class NowMonth(View):

# 	""" 本月到期用户 """
# 	def get(self, request):
# 		try:
# 			# 查询
# 			obj = Admin_after()
# 			query_data = obj.now_month()
# 		except Exception as e:
# 			return JsonResponse({"status": False, 'result': '查询数据库失败', 'e': e})

# 		try:
# 			# 组织数据
# 			result = after_data(query_data)
# 		except Exception as e:
# 			return JsonResponse({"status": False, 'result': '组织数据失败'})

# 		return JsonResponse({"status": True, 'result': result,"datalen":len(result)})

# class NextMonth(View):

# 	""" 下月到期用户 """
# 	def get(self, request):
# 		try:
# 			# 查询
# 			obj = Admin_after()
# 			query_data = obj.next_month()
# 		except Exception as e:
# 			return JsonResponse({"status": False, 'result': '查询数据库失败', 'e': e})

# 		try:
# 			# 组织数据
# 			result = after_data(query_data)
# 		except Exception as e:
# 			return JsonResponse({"status": False, 'result': '组织数据失败'})

# 		return JsonResponse({"status": True, 'result': result,"datalen":len(result)})


class SelectVip(View):
    """vip等级用户资料"""

    def get(self, request):
        page = request.GET.get('page')
        level = request.GET.get('level')

        try:
            page = (int(page) - 1) * 25
        except Exception as e:
            return JsonResponse({"status": False, 'result': '参数错误'})

        number = 0  # 人数
        try:
            # 查询
            obj = Admin_after()
            q = obj.vip_level_num(level)
            query_data = obj.vip_level(page, level)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '查询数据库失败', 'e': str(e)})

        try:
            # 组织数据
            result = after_data(query_data)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '组织数据失败'})

        if q:
            number = q

        return JsonResponse({"status": True, 'result': result, "number": number})


class SelectUserName(View):
    """指定用户资料"""

    def get(self, request):
        username = request.GET.get('username')
        try:
            # 查询
            obj = Admin_after()
            query_data = obj.select_username(username)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '查询数据库失败', 'e': e})

        try:
            # 组织数据
            result = after_data(query_data)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '组织数据失败'})

        return JsonResponse({"status": True, 'result': result})


class Unbundling(View):
    """解绑视图"""

    def post(self, request):
        username = request.POST.get('username')
        try:
            # 查询
            obj = Admin_after()
            is_bool = obj.unbundling(username)
            if not is_bool:
                return JsonResponse({"status": False, 'result': '无此用户名'})
            query_data = obj.select_username(username)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '查询数据库失败'})

        try:
            # 组织数据
            result = after_data(query_data)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '组织数据失败'})

        return JsonResponse({"status": True, 'result': result, 'state': '解绑成功'})


class ActivationVip(View):
    """激活视图"""

    def post(self, request):
        username = request.POST.get('username')
        statdate = request.POST.get('time')
        level = request.POST.get('level')

        try:
            # 处理参数
            s = datetime.datetime.now().strftime(" %H:%M:%S")
            statdate = datetime.datetime.strptime(statdate + s, '%Y-%m-%d %H:%M:%S')
        except Exception as e:
            return JsonResponse({"status": False, 'result': '参数有误'})

        try:
            # 查询
            obj = Admin_after()
            is_bool = obj.activation_vip(username, statdate, level)
            if not is_bool:
                return JsonResponse({"status": False, 'result': '无此用户名'})
            query_data = obj.select_username(username)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '查询数据库失败'})

        try:
            # 组织数据
            result = after_data(query_data)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '组织数据失败'})

        return JsonResponse({"status": True, 'result': result, 'state': '激活成功'})


class DeleteUser(View):
    """删除用户视图"""

    def post(self, request):
        usernames = request.POST.get('username')
        try:
            username_list = usernames.split(',')
            username_list.append(' ')
            username = tuple(username_list)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '参数错误'})

        try:
            # 删除
            obj = Admin_after()
            is_bool = obj.delete_user(username)
            if not is_bool:
                return JsonResponse({"status": False, 'result': '无此用户名'})
        except Exception as e:
            return JsonResponse({"status": False, 'result': '数据库操作失败'})

        return JsonResponse({"status": True, 'result': '删除成功'})


class UpdateUserQQ(View):
    """用户修改QQ"""

    def post(self, request):
        qq = request.POST.get('qq')
        username = request.POST.get('username')

        try:
            # 添加
            obj = Admin_after()
            obj.update_user_qq(username, qq)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '数据库错误', 'e': str(e)})

        return JsonResponse({"status": True, 'result': '修改成功'})


class UpdateUserWX(View):
    """用户修改微信"""

    def post(self, request):
        wx = request.POST.get('wx')
        username = request.POST.get('username')

        try:
            # 添加
            obj = Admin_after()
            obj.update_user_wx(username, wx)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '数据库错误', 'e': str(e)})

        return JsonResponse({"status": True, 'result': '修改成功'})


class CrowdPorrtaitCat(View):
    """人群画像类目视图"""

    def post(self, request):
        """获取类目"""
        cookie = request.POST.get('taobao')
        try:
            cookie = json.loads(cookie)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '参数错误'})
        try:
            crowd_obj = PortraitCrowd()
            crowd_obj.cookies = cookie
            data = crowd_obj.GetClass()
        except Exception as e:
            return JsonResponse({"status": False, 'result': '爬取失败', 'e': str(e)})
        try:
            if data['code'] == 5810:
                return JsonResponse({"status": False, 'result': '淘宝登录过期'})
        except Exception as e:
            pass
        if not data['data']:
            return JsonResponse({"status": False, 'result': '你的生意参谋账号不具备使用该功能、，请升级生意参谋账号后再来使用！'})

        return JsonResponse({"status": True, 'result': data})


class CrowdPortrait(View):
    """人群画像数据视图"""

    def post(self, request):
        cookie = request.POST.get('taobao')
        goods_id = request.POST.get('goods')
        cateid = request.POST.get('catid')

        if not all([cookie, goods_id, cateid]):
            return JsonResponse({"status": False, 'result': '参数缺省'})

        try:
            cookie = eval(cookie)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '参数错误'})

        try:
            # 调用爬虫
            crawler_obj = PortraitCrowd()
            crawler_obj.cookies = cookie
            TenKeyword = crawler_obj.GetKeyword(goods_id)
            crawler_obj.cateId = cateid
            crawler_data = crawler_obj.mian(TenKeyword)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '爬虫异常', 'e': str(e)})
        try:
            if crawler_data['code'] == 5810:
                return JsonResponse({"status": False, 'result': '淘宝登录过期'})
            elif crawler_data['code'] == 1100:
                return JsonResponse({"status": False, 'result': ' %s :id错误，请输入绑定店铺商品id' % goods_id})
        except Exception as e:
            pass

        try:
            # 数据处理
            data = crowd_portrait_place(crawler_data)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '数据处理失败'})

        # try:
            # 收据存储
        gender_variance = data['gender']['variance']
        age_variance = data['age']['variance']
        city_variance = []
        for i in data['city']['base']:
            if float(i[12]):
                city_variance.append(i[0])
                city_variance.append(i[12])
        CrowdPortraitSQL(gender_variance, age_variance, city_variance)
        # except Exception as e:
        #     return JsonResponse({"status": False, 'result': '数据存储失败'})

        try:
            # 打分
            women_variance = gender_variance[0]
            city_rate_variance = data['city']['city_rate']
            num = Crowd_Portrait(women_variance, age_variance, city_rate_variance)
            data['score'] = round(num, 2)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '打分失败', 'e': str(e)})

        return JsonResponse({"status": True, 'result': data})


class UserStatisticalView(View):
    """用户统计视图"""

    def get(self, request):
        start_time = request.GET.get('start_time')
        end_time = request.GET.get('end_time')

        sum = []
        try:
            # 查询
            for i in range(6):
                query = sel_user_statistical(i, start_time, end_time)
                sum.append(query)
        except Exception as e:
            return JsonResponse({"code": 400, "status": False, 'result': '查询失败', "data": []})

        data = []
        try:
            # 数据
            for i in sum:
                a = {
                    "vip_level": i[0],
                    "user_num": str(i[1]),
                    "new_user": str(i[2]),
                    "to_user": str(i[3]),
                    "upgrade_user": str(i[4]) if i[4] else "0",
                    "sms_contact": str(i[5]) if i[5] else "0",
                    "phone_contact": str(i[6]) if i[6] else "0",
                    "problem_feedback": str(i[7]) if i[7] else "0",
                    "problem_solve": str(i[8]) if i[8] else "0",
                    "diagnosis": str(i[9]) if i[9] else "0"
                }
                data.append(a)
        except Exception as e:
            return JsonResponse({"code": 400, "status": False, 'result': '数据失败', "data": []})

        return JsonResponse({"code": 200, "status": True, 'result': 'OK', "data": data})

    def post(self, request):
        vip_level = request.POST.get('vip_level')
        upgrade_user = request.POST.get('upgrade_user')
        sms_contact = request.POST.get('sms_contact')
        phone_contact = request.POST.get('phone_contact')
        problem_feedback = request.POST.get('problem_feedback')
        problem_solve = request.POST.get('problem_solve')
        diagnosis = request.POST.get('diagnosis')

        statdate = int(time.mktime(time.strptime(datetime.datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d'))) - 86400

        try:
            upgrade_user = int(upgrade_user)
            sms_contact = int(sms_contact)
            phone_contact = int(phone_contact)
            problem_feedback = int(problem_feedback)
            problem_solve = int(problem_solve)
            diagnosis = int(diagnosis)
        except Exception as e:
            return JsonResponse({"code": 400, "status": False, "result": '参数错误', "data": []})

        try:
            # 存储
            user_sta_obj = UserStatisticalSQL(vip_level, statdate, upgrade_user, sms_contact, phone_contact,
                                              problem_feedback, problem_solve, diagnosis)  # 实例
            user_sta_obj.save_data()
        except Exception as e:
            return JsonResponse({"code": 400, "status": False, "result": '存储错误', "data": []})

        return JsonResponse({"code": 200, "status": True, "result": 'OK', "data": []})


class SelLevelDueToView(View):
    """不同等级到期用户"""

    def get(self, request, pk):
        page = request.GET.get('page')
        level = request.GET.get('level')

        try:
            page = (int(page) - 1) * 25
        except Exception as e:
            return JsonResponse({"status": False, 'result': '参数错误'})

        number = 0  # 人数

        sel_obj = sel_due_to(page, level)  # 实例
        if pk == "1":
            sql, q = sel_obj.due_to()
        elif pk == "2":
            sql, q = sel_obj.this_month()
        elif pk == "3":
            sql, q = sel_obj.next_month()
        else:
            return JsonResponse({"status": False, 'result': 'url错误'})

        try:
            # 查询
            query = sel_obj.main(sql)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '查询错误'})

        try:
            # 组织数据
            result = after_data(query)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '组织错误'})

        if q:
            number = q[0]

        return JsonResponse({"status": True, 'result': result, "number": number})


class RegisteredTimeView(View):
    """注册时间查询"""

    def get(self, request, pk):
        page = request.GET.get('page')

        try:
            page = (int(page) - 1) * 25
        except Exception as e:
            return JsonResponse({"status": False, 'result': '参数错误'})

        number = 0  # 人数

        sel_obj = registered_time(page)  # 实例

        if pk == "1":
            sql, q = sel_obj.day_1()
        elif pk == "2":
            sql, q = sel_obj.day_3()
        elif pk == "3":
            sql, q = sel_obj.day_7()
        else:
            return JsonResponse({"status": False, 'result': 'url错误'})

        try:
            # 查询
            query = sel_obj.main(sql)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '查询错误'})

        try:
            # 组织数据
            result = after_data(query)
        except Exception as e:
            return JsonResponse({"status": False, 'result': '组织错误'})

        if q:
            number = q[0]

        return JsonResponse({"status": True, 'result': result, "number": number})


class UserExpand(View):
    """用户拓展信息录入，修改"""

    def post(self, request):
        user_name = request.POST.get('user_name')
        zd_nickname = request.POST.get('zd_nickname')
        zd_passwd = request.POST.get('zd_passwd')
        pay_date = request.POST.get('pay_date')
        is_diagnosis = request.POST.get('is_diagnosis')
        statdate = int(time.mktime(time.strptime(datetime.datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d')))  # 录入时间
        DB, Cursor = Link_database()
        CheckName_Sql = """ select * from user_expand where user_name = '%s' """ % (user_name)
        Cursor.execute(CheckName_Sql)
        if Cursor.fetchone():
            # 更改数量情况

            Updata_Sql = """ UPDATE user_expand SET statdate = %d, zd_nickname = '%s',	zd_passwd = '%s', pay_date = '%s',is_diagnosis = '%s' WHERE  user_name = '%s' """ % (
            statdate,
            zd_nickname, zd_passwd, pay_date, is_diagnosis, user_name)
            Cursor.execute(Updata_Sql)
            DB.commit()
            result = "更改成功！"
        else:
            # 新增设备
            inset_sql = """ INSERT INTO  user_expand (statdate,user_name,zd_nickname, zd_passwd, pay_date,is_diagnosis) VALUES (%d,'%s','%s','%s','%s','%s') """ % (
            statdate, user_name, zd_nickname, zd_passwd, pay_date, is_diagnosis)
            Cursor.execute(inset_sql)
            DB.commit()
            result = "新增成功！"
        DB.close()
        Cursor.close()
        return JsonResponse({"code": 200, "result": result, "data": []})


class UserExpandRepeat(View):
    """ 需要重复记录的用户信息录入 """

    def post(self, request):
        user_name = request.POST.get('user_name')
        pay_status = request.POST.get('pay_status')
        online_contact_date = request.POST.get('online_contact_date')
        dl_date = request.POST.get('dl_date')
        feedback_record = request.POST.get('feedback_record')
        file = request.FILES.get('chat_record')
        statdate = int(time.mktime(time.strptime(datetime.datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d')))  # 录入时间

        # 文件处理
        if file != None:
            times = str(int(time.time()))
            if (hostname()) == 'DESKTOP-424AROC':  # 判断是本地还是服务器
                file_address = times + '.doc'
            else:
                file_address = '/home/OA/FinancialStatements/' + times + '.doc'

            with open(file_address, 'wb') as f:
                f.write(file.read())
            DB, Cursor = Link_database()
            file_address = 'https://oa.yuetaosem.com:85/FinancialStatements/' + times + '.doc'
        else:
            file_address = ''
        DB, Cursor = Link_database()

        inset_sql = """ INSERT INTO  expand_repeat
		(user_name,pay_status,online_contact_date,dl_date,feedback_record,chat_record,statdate) 
		VALUES ('%s','%s','%s','%s','%s','%s',%d) """ % (
        user_name, pay_status, online_contact_date, dl_date, feedback_record, file_address, statdate)
        try:
            Cursor.execute(inset_sql)
            DB.commit()
            result = "新增成功！"
            code = 200
        except:
            result = "操作数据库失败!"
            code = 400

        DB.close()
        Cursor.close()
        return JsonResponse({"code": code, "result": result, "data": []})


class ExpandRepeatQuery(View):
    """" 用户可叠加数据查询 """

    def userExpandRepeat(self, user_name):

        """ 用户可叠加信息查询 """
        DB, Cursor = Link_database()

        sql = """ select statdate,pay_status,online_contact_date,dl_date,feedback_record,chat_record from expand_repeat where user_name = '%s' """ % (
            user_name)
        Cursor.execute(sql)
        AttendanceData = Cursor.fetchall()
        statdateList = []
        pay_statusList = []
        online_contact_dateList = []
        dl_dateList = []
        feedback_recordList = []
        chat_recordList = []
        weekList = []

        now = datetime.datetime.now()
        this_week_start = str(now - timedelta(days=now.weekday())).split(" ")[0]
        this_week_end = str(now + timedelta(days=6 - now.weekday())).split(" ")[0]
        for ad in AttendanceData:

            if ad[0] != "None":
                statdateList.append(ad[0])
            if ad[1] != "None":
                pay_statusList.append(ad[1])
            if ad[2] != "None":
                if this_week_start <= ad[2] <= this_week_end:
                    weekList.append(ad[2])
                online_contact_dateList.append(ad[2])
            if ad[3] != "None":
                if this_week_start <= ad[3] <= this_week_end:
                    weekList.append(ad[3])
                dl_dateList.append(ad[3])
            if ad[4] != "None":
                feedback_recordList.append(ad[4])
            if ad[5] != "":
                chat_recordList.append(ad[5])

        DB.close()
        Cursor.close()
        return {"statdate": statdateList, "pay_status": pay_statusList, "online_contact_date": online_contact_dateList,
                "dl_date": dl_dateList, "feedback_record": feedback_recordList, "chat_record": chat_recordList,
                "week_lx": len(weekList), "history_lx": len(online_contact_dateList) + len(dl_dateList)}

    def post(self, request):
        user_name = request.POST.get('user_name')

        try:
            result = self.userExpandRepeat(user_name)
            code = 200
        except:
            result = "数据查询失败！"
            code = 400
        return JsonResponse({"code": code, "result": result, "data": []})
